For loop Help!!

Jun 7, 2016 at 4:15am
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;
}
Jun 7, 2016 at 4:47am
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 Jun 7, 2016 at 6:29am
Jun 7, 2016 at 4:51am
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 Jun 7, 2016 at 4:52am
Jun 7, 2016 at 12:35pm
Thanks a lot
Topic archived. No new replies allowed.