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 we complete the body of the for
loop each time.
The following sequence of diagrams explain the progression of the for
loop:
for
loop that will gather the sum of the numbers from 1 to 10.for
loop that will print the multiples of 6, from 6 to 30 (6, 12, 18, 24, and 30).for
loop that will print numbers 2 to 100 in multiples of 2 (for example, 2, 4, 6, 8, and so on).for
loop that will print numbers 1 to 16 and their squares beside them.Here are the solutions for the preceding exercises:
for
loop for printing the sum of the numbers from 1 to 10 is as follows:int sum = 0; for( int x = 1; x <= 10; x++ ) { sum += x; cout << x << endl; }
for
loop for printing multiples of 6 from 30 is as follows:for( int x = 6; x <= 30; x += 6 ) { cout << x << endl; }
for
loop for printing numbers from 2 to 100 in multiples of 2 is as follows:for( int x = 2; x <= 100; x += 2 ) { cout << x << endl; }
for
loop that prints numbers from 1 to 16 and their squares is as follows:for( int x = 1; x <= 16; x++ ) { cout << x << " " << x*x << endl; }
3.144.39.144