The for loop is the counting loop of C++. It is usually designed to run a specific number of times, and then end. With it, it keeps a counter, to let you know where in the loop you are – useful when looping through an array which will look at soon enough.
The general form of the for loop is:
for(<variable initialize>; <condition>; <variable modifier>)
{
// loop body
}
This can make certain loops much easier to write. Consider the following while loop.
int counter = 0;
while (counter < 10)
{
// loop body
counter++;
}
Now look at the same logic, but with a for loop:
for(int counter = 0; counter < 10; counter++)
{
// loop body
}
Notice how all of the looping logic and structure is easily contained in the loop declaration.
If you declare the variable in the initialization phase, it can only be used inside the for loop, but it doesn’t have to be declared there, you can set another value.
int counter; // counter can be used anywhere
for(counter = 0; counter < 10; counter++)
{
}
for(int i = 0; i < 10; i++)
{
// i can only be used inside the for loop
}
While rarely needed, you can have multiple statements in the initialization and modifier stage. A common situation is when you have a nested loop, or a loop within another loop.
for( int i = 0, int j; i < 10; i++)
{
for( j = 0; j < 10; j++)
{
// inner loop body
}
}
You can make a for loop act like a while loop, but it is bad form. The for loop and while loop server two different purposes – making code easy to read/write/debug means choosing the right code for the right job.
For Loops in C++ was originally found on Access 2 Learn