Hi,
this is the syntax for 'For' loop. I hope u know that a loop is a structure
where u execute some code continuously until some condition is satisfied.
then u end the execution of code. Basically when u start a loop u can either
run it as a infinite loop (ie it never stops) or give a condition. to come
out of it once the condition is satisfied.
here is a small example where loop is executed 10 times.
int i =0;
while(i<10)
{
printf("hello world %d\n",i);
i = i + 1;
}
Basically the code ie printf() is executed 10 times. How do I track the
number of times the loop executed? I use a integer variable (counter). I
initialize it to 0. I start the loop. While starting I check the condition
whether the loop has executed for 10 times by checking the value of 'i', If
'i' is less than 10 then the loop has not been executed for 10 times. it
goes inside the loop, executes the printf() function and add 1 to 'i' and
the process is repeated till 'i' becomes 10.
The same thing if u want to do with lesser lines of code, u use the 'for'
loop
here is the syntax:
for (expression1; expression2; expression3)
{statement}
Here is the same code converted to using 'for' loop
int i;
for(i=0;i<10;i=i+1)
printf("hello world %d\n",i);
In the 'for' loop
expression1 is the initializing part where u do the initiallizing of the
counter variable
expression2 is the condition checking part where u check when the loop
has to end.
expression3 is the incrementing part where u increment or add the
counter variable
when this code is executed, in the first iteration of loop the expression1
is evaluated, then expression2, then the code ie printf() is executed, then
expression3 is evaluated. In all the next subsequent iterations, expression2
is evaluated first, then code is executed and then expression3 is evaluated.
Hope that helps.
Girish.