The for loop
The
for
loop has a slightly different anatomy than the while
loop, but both are very similar.
Let's examine the anatomy of a for
loop as compared to an equivalent while
loop. Take an example of the following code snippets:
The for loop |
An equivalent while loop |
---|---|
for( int x = 1; x <= 5; x++ ) { cout << x << endl; }
|
int x = 1; while( x <= 5 ) { cout << x << endl; x++; }
|
The for
loop has three statements inside its brackets. Let's examine them in order.
The first statement of the for
loop (int x = 1
;) only gets executed once, when we first enter the body of the for
loop. It is typically used to initialize the value of the loop's counter variable (in this case, the variable x
). The second statement inside the for
loop (x <= 5
;) is the loop's repeat condition. As long as x <= 5
, we must continue to stay inside the body of the for
loop. The last statement inside the brackets of the for
loop (x++
;) gets executed after...