Its format is:
1 2 3 | for (initialization; condition; increase) statement; |
and its main function is to repeat statement while condition remains true, like the while loop. But in addition, for provides places to specify an initialization instruction and an increase instruction. So this loop is specially designed to perform a repetitive action with a counter.
It works the following way:
- initialization is executed. Generally it is an initial value setting for a counter varible. This is executed only once.
- condition is checked, if it is true the loop continues, otherwise the loop finishes and statement is skipped.
- statement is executed. As usual, it can be either a single instruction or a block of instructions enclosed within curly brackets { }.
- finally, whatever is specified in the increase field is executed and the loop gets back to step 2.
Here is an example of countdown using a for loop.
1 2 3 4 5 6 7 8 9 10 11 12 | // countdown using a for loop #include <iostream.h> int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!"; return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> using namespace std; int main () { // for loop execution for( int a = 10; a < 20; a = a + 1 ) { cout << "value of a: " << a << endl; } return 0; } |