having trouble using for loops..

HIhi, I've been trying out the great beginner exercises in this site, and I've got pretty stuck on using for loops.
due to using matlab a lot, I think I'm probably getting confused on what I can use and what I can't, but I just can't find what's wrong.

1
2
3
4
for(int num=1; num<=10; num++)
	{
		cout << "person " << whichman[num] << ": ate " << pancakemen[num] << " pancakes" << endl;
	}


the output comes out as the variable 'num' always being 1 when inside cout.
Can anyone help?
Last edited on
Hi Joon,

In C and C++, arrays start at zero and end at size -1.

So what is happening here is you are missing out the first one whichman[0], and going past the end whichman[10] - last one is whichman[9].

Rather than have magic number like 10 in your code, make them a constant variable, and get used to using this idiom of starting at zero:

1
2
3
4
5
const int Size = 10;

for(int num=0; num < Size ; num++) {
		cout << "person " << whichman[num] << ": ate " << pancakemen[num] << " pancakes" << endl;
}


Hope all goes well :+)

Edit: Did you initialise your arrays?
Last edited on
Topic archived. No new replies allowed.