C++ for loop repetition statement



The for Loop in C++

The for loop is a pretest loop that combines the initialization, testing, and updating of a loop control variable in a single loop header. A loop that repeats a specific number of times is known as a count-controlled loop.

For example, if a loop asks the user to enter the sales amounts for each month in the year, it will iterate twelve times. In essence, the loop counts to twelve and asks the user to enter a sales amount each time it makes a count.

A count-controlled loop must possess three elements:

  1. It must initialize a counter variable to a starting value.
  2. It must test the counter variable by comparing it to a final value. When the counter variable reaches its final value, the loop terminates.
  3. It must update the counter variable during each iteration. This is usually done by incrementing the variable.

Count-controlled loops are so common that C++ provides a type of loop specifically for them. It is known as the for loop. The for loop is specifically designed to initialize, test, and update a counter variable.

Here is the format of the for loop :


    for (initialization; test; update)
    {
    statement;
    statement;
    // Place as many statements
    // here as necessary.
    }

As with the other loops you have used, if there is only one statement in the loop body, the braces may be omitted. Here is an example of a simple for loop that prints “Hello World!” three times:


    for (count = 1; count <= 3; count++)
    cout << "Hello World!" << endl;

In this loop, the initialization expression is count = 1, the test expression is count <= 3, and the update expression is count++. The body of the loop has one statement, which is the cout statement. The program below displays the numbers 1–5 and their squares by using a for loop.


    // This program uses a for loop to display the numbers 1-5
    // and their squares.
    #include <iostream.h>
    #include <iomanip.h>
    using namespace std;
    
    int main()
    { 
    int nr;
     cout << "Number Squared\n";
     cout << "--------------\n";
     for (nr = 1; nr <= 5; nr++)
     cout << setw(4) << nr << setw(7) << (nr * nr) << endl;
     return 0;
     }

    Output with Example Input Shown in Bold:

    Number      Squared
    ------------------
    1               1
    2               4
    3               9
    4               16
    5               25

Ads Right