For loop Help!!

I need help with printing this array. Also, a brief explanation of the for loop would be helpful.

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

int main() {
	
	int grades[5] = {6,3,2,5,7};

	for (int g = 1; g <= 5; g++) {
		cout << grades[g] << endl;
	}
	
	system("pause");
	return 0;
}
closed account (48T7M4Gy)
for(int g = 0; g < 5 ... etc because the first element of the array is grades[0]

grades[5] is outside the range of grades you defined in line 6 and will just be a junk number, whatever is in uncontrolled memory at the time.

Check the tutorials on this site for an explanation of how the for loop works.
Last edited on
Arrays start at index 0, and go up to index SIZE-1. Meaning, if you declare an array of size 5, the indices of that array go from 0 to 4.

There are two mistakes in your for-loop:
(1) You are starting at 1, and therefore completely skipping over grades[0]
(2) You loop up to and including 5, and are therefore trying to access grades[5] which I already explained does NOT exist. It is out of the bounds of the array.

Your for-loop should look like this:

1
2
3
4
	
    for (int g = 0; g < 5; g++) {
		cout << grades[g] << endl;
	}


Notice that it starts at g=0, and goes up to g<5 i.e. it will stop at g=4.

This will print the entire array from grades[0] to grades[4].
Last edited on
Thanks a lot
Topic archived. No new replies allowed.