Can you help me understand this basic thing ?

I have been trying to learn C programming from some webpages I downloaded but I find I cannot work this out and the webpage leaves me none the wiser.


int a[5];
int i;

for (i=0; i<5; i++)
a[i] = 0;

How does the above actually work it's meant to initialize all the numbers in the array to 0 but I can't work out how it moves onto a[2] or [a3] if i=0 set's i to 0 every single time then it will be less than five so i++ will make it one but when it loops how can it become a[2] if i=0 keeps setting it to 0 this confuses me.

Any answers would be most gratefully accepted, thanks ?.

philip70
int a[5];

Your creating a array with five elements inside of it(no value given yet).

int i;

Your creating a integer(no value given yet).

for(i=0;i<5;i++)

Creating a for loop that will create a temporary integer named 'i' to represent 0, after that it will compare integer 'i' value to the value of 5. Then to finish the statement it will add 1 to the value of 'i'.

a[i]=0;

Giving array 'a' a element number via the integer 'i' and then inserting a value '0'.

correct code is
1
2
3
4
5
int a[5];
int i;

for (i=0; i<5; i++){
a[i] = 0;}


You forgot to put the brackets to signify what the for loop would actually effect.

P.S. make your description on what you want to accomplish on your code more clear.
Last edited on
closed account (zb0S216C)
Factors wrote:
for(i=0;i<5;i++)

Creating a for loop that will create a temporary integer named 'i'

Not quite. i was already defined. Look again at the declaration section of for.

Factors wrote:
You forgot to put the brackets to signify what the for loop would actually effect.

Actually, omitting the braces is valid, but the loop is only allowed to execute 1 statement (the statement that immediately follows it).

Edit: Post count = this year :)

Wazzak
Last edited on
i++ increments the i variable.

So...

1
2
3
int i = 0;  // i == 0
i++;  // now, i == 1
i++;  // now, i == 2 


The way for loops work:

 
for( initialization; condition; increment )


'initialization' is done exactly once, when the loop is first started.

'condition' is done before the loop takes another iteration.

'increment' is done after the loop completes an iteration.


So basically how this works....

1
2
for (i=0; i<5; i++)
  a[i] = 0;


The computer will do the following:

1) Do the for loop initialization (i=0)
2) Check the loop condition (i<5 .. which is true). Since it's true, it will perform the loop
3) perform loop body (a[i] = 0, since i=0, this means a[0] = 0)
4) Now that the loop body is complete, do the loop increment (i++). Now, i=1
5) Check loop condition again (i<5, which is still true).
6) Do the loop body again. This time i=1, so a[1] = 0
7) Increment again, i=2
//...

It eventually stops when i=5, because (i<5) is no longer true.


EDIT: doh, too slow. Ninja'd twice!
Last edited on
Cheers thank you so much for your forbearance and your help :-)
Topic archived. No new replies allowed.