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 we complete the body of the for loop each time.

The following sequence of diagrams explain the progression of the for loop:

The for loop

Exercises

  1. Write a for loop that will gather the sum of the numbers from 1 to 10.
  2. Write a for loop that will print the multiples of 6, from 6 to 30 (6, 12, 18, 24, and 30).
  3. Write a for loop that will print numbers 2 to 100 in multiples of 2 (for example, 2, 4, 6, 8, and so on).
  4. Write a for loop that will print numbers 1 to 16 and their squares beside them.

Solutions

Here are the solutions for the preceding exercises:

  1. The solution for the 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;
    }
  2. The solution for the for loop for printing multiples of 6 from 30 is as follows:
    for( int x = 6; x <= 30; x += 6 )
    {
      cout << x << endl;
    }
  3. The solution for the 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;
    }
  4. The solution for the 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;
    }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.39.144