for Loops
#
Another type of loop that we can use is the for loop. It is a special case of the while loop that is easier to read in some cases when the purpose of the loop is counting. This is an affordance to us humans as the compiler will likely emit the same machine code for both loops regardless.
The for loop takes the three parts of the while loop that we encounter when writing a while loop that counts:
int i = 0;
while(i < 10)
{
printf("%d",i);
i++;
}
and arranges them all on the same line for convenience. When we want to understand a for loop all we have to do is look at the first line:
for(int i = 0; i < 10; i++)
{
printf("%d",i);
i++;
}
If you initialize the variable i within the for loop as in the example above it will only be available inside of the for loop and once it reaches the end of the for loop it will cease to exist. This is known as the scope of the variable, usually variables are available within their scope, the set of {} brackets in which the variable was created.