DSA FUNDAMENTALS › ARRAY BASICS
The array [4, 2, 7, 1] has four slots. Each slot has a position called its index and a piece of stored data called its element value. Array indices start at 0, so the first slot has index 0 and the last slot has index 3. The value 7 is stored in the slot at index 2.
| INDEX | ELEMENT VALUE |
|---|---|
| 0 | 4 |
| 1 | 2 |
| 2 | 7 |
| 3 | 1 |
The index and the element value can be different numbers. In this array, index 0 locates the value 4, and index 2 locates the value 7. The number below a slot tells you where the slot is. The number inside the slot is the data you can read.
Which description correctly identifies the slot containing 7?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
When a loop variable i moves through this array, it takes the index values 0, 1, 2, and 3. For each value of i, arr[i] reads the element value in the slot at that index. The pair changes together as the loop moves: i = 0 gives arr[0] = 4, i = 1 gives arr[1] = 2, i = 2 gives arr[2] = 7, and i = 3 gives arr[3] = 1.
| I | SLOT LOCATED | ARR[I] |
|---|---|---|
| 0 | index 0 | 4 |
| 1 | index 1 | 2 |
| 2 | index 2 | 7 |
| 3 | index 3 | 1 |
At i = 2, the loop variable is not the element value 7. It is the location used inside arr[i]. The expression arr[2] evaluates to 7 because index 2 points to the slot where 7 is stored. Printing i would print 2, while printing arr[i] would print 7.
For this array, n is 4, so the loop starts with i = 0 and tests i < 4. The test is true, the loop reads index 0, and then i increases by 1. The same steps read indices 1, 2, and 3. After index 3, the increment makes i equal to 4, and the test i < 4 becomes false.
The loop stops before trying to read arr[4]. The valid indices end at 3 because the array has four slots and indexing starts at 0. This boundary gives exactly four iterations, one for each slot.
Replace the incorrect condition i <= n with the condition that safely visits all four slots of [4, 2, 7, 1].
for (int i = 0; i <= n; i++) {
print(arr[i]);
}Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The loop prints two expressions on each iteration. The first expression is i, which supplies the current index. The second expression is arr[i], which supplies the element value stored at that index. Combining them with the required text produces one line for each slot.
int arr[] = {4, 2, 7, 1};
int n = 4;
for (int i = 0; i < n; i++) {
cout << "Index " << i << ": " << arr[i] << endl;
}int[] arr = {4, 2, 7, 1};
int n = 4;
for (int i = 0; i < n; i++) {
System.out.println("Index " + i + ": " + arr[i]);
}Index 0: 4
Index 1: 2
Index 2: 7
Index 3: 1