help with arrays

hi everybody, so i have an exam next week and i was practicing and i found this code, can you explain to me why when i run it, it gives me a[1] = 20 and a[3] = 17. thank you.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main(){
int marks[5]={10, 20, 15, 17, 9};
for(int i=0; i<4; i++)
	if(marks[i]>marks[i+1]){
	cout << "a["<<i<<"] = " << marks[i] << endl;
}
	return 0;
}
Last edited on
The script iterates through your marks[] array and checks, if the current value (marks[i]) is greater than the following (marks[i++] = marks[i+1]).

That means:
i = 0
10 is NOT greater than 20. It won't be printed.
i = 1
20 is greater than 15. It will be printed.
i = 2
15 is NOT greater than 17. It won't be printed.
i = 3
17 is greater than 9. It will be printed.

i cannot reach four because 4+1 would be 5 and marks[5] would cause an access violation because only the values marks[0] to marks[4] exist.
Line 5 declares an array (called marks, not a) of 5 elements. It initialises these 5 elements to the values within the braces. Since array indices start at 0, we have, in particular,
marks[0]=10
marks[1]=20
...
marks[4]=9

A standard for loop begins on line 6 (and ends on line 9, although this is far from obvious) which considers values i=0,1,2,3 in turn.

Within the loop it compares marks[i] with the marks at the next position in the marks array and, if this comparison is true (ie marks at one index exceed those at the next) it does whatever is within the brace pair following the if statement (in this case, opening on line 7 and closing on line 9). Here, the if condition is true when i=1 (because 20>15) and when i=3 (because 17>9). This is what it writes to screen on line 8.

The program is badly laid out because:
- the indenting is inconsistent, making structure difficult to follow;
- the limits of the loop are not easy to see because they aren't delimited by braces (that on line 9 refers to the if statement, despite its positioning suggesting the for loop);
- the array is called marks, not a.
understood, thank you very much.
Registered users can post here. Sign in or register to post.