For Loop Variables and how this would work. :S

Hello everyone.

I am learning C++ and am currently having trouble grasping one thing to do with for loops. When you initialize a variable for a for loop that will cycle through an array, how does this work:

int i;
int nums[10];

for(i=0, i < 10, i++) { nums[i] += i; }
^ Does this variable have anything to do with the one I initialized above.
And does the variable in nums[i](the i) have anything to do with either of the two.

I know that you cannot use a local variable inside a block of code that it wasn't initialized, so the loop wouldn't have anything to do with the i that I created in the beginning of main. So I guess what I am asking is, how does the 'i' in numbs[] get affected and how does it work with the for loop?

Thank you. (Sorry if in the wrong forum.)
Dear steohenP,
probabily you have not understood the cocept of arrays and loops.
I would advice you go through these concepts in tutorials given at this site.
As for your question both i's used in for loop and in the block are same
this for loop does nothing but it puts the values in array num

and the i used here is declared in the first line of code
working of the loop is as follows:-

for i=0, num[0]=num[0]+0;
for i=1, num[1]=num[1]+1;
......tilli<10

Hope your problem is solved now
with regards,
matanuragi
I did go over some, I've gone through several books, but I guess I'm just a tad slow or incompetent when it comes to learning. Thank you for your help.
Your concept of scope is sort of backwards. Right now, i is local to main. The for loop is within main, so i is accessible within the for loop. If i had been declared inside the loop, then it would not be accessible outside of that loop.
Check out scope of variables:
http://www.cplusplus.com/doc/tutorial/variables.html
Isn't it

for (i=0; i < 10; i++) {
}

instead of

for(i=0, i < 10, i++) {
}

? a comma is for more numbers, like

for(i=0, kip=7; i < 10; ++i, --kip) {
}
Ahh, alright, thank you. Now I get it. :D

Thanks.
And yes, you are right Jyy, that was a typo. I'm kinda used to another language.
Last edited on
Topic archived. No new replies allowed.