3 minute briefing on for

The last command I am going to talk about in this series is the command for. Together with the variables, while, and if it makes about 80% of all programming, the secret is only to put them together in a meaningful way. For is technically nothing else than a sophisticated while command. for allows you to execute a command a set couple of times:

int i;
for(i=0;i<100;i++)
     printf("%i\n",i);

The above code does the following: In the first part of the for command it sets i=0 and then executes the next line (the printf) as long as i<100 - very similar to the while from last time, and technically they are the same. Lastly there is this i++ which is first of all a fancy way of saying i=i+1 but also this little thingy gets executed every time as well. There for the above code does exactly the same as:

int i;
i=0;
while(i<100){
     printf("%i\n",i);
     i=i+1;
}

It if just easier to write the for loop than the multiple lines the while requires.

Cheers Arend

Leave a Reply