for loop in c++


  • A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
  • The for statement allows you to execute a block of code a specified number of times.
  • The for loop is a generic iterator in C++, it can step through the items in any ordered sequence or other iterable object.
  • C++ provides a specialized loop that packages these four programming elements into one convenient statement. Called the for loop.

Syntax

    for ( initialization ; condition ; modification )
    {
        statement;
    }
  • The reserved word for identifies a for statement.
  • The loop is controlled by a special variable called the loop variable.
  • The header, contained in parentheses, contains three parts, each separated by semicolons:
    • Initialization:The initialization part assigns an initial value to the loop variable. The loop variable may be declared here as well; if it is declared here, then its scope is limited to the for statement. This means you may use that loop variable only within the loop. It also means you are free to reuse that variable‚Äôs name outside the loop to declare a different variable with the same name as the loop variable. The initialization part is performed one time.
    • Condition: The condition part is a Boolean expression, just like the condition of a while statement. The condition is checked each time before the body is executed.
    • Modification: The modification part generally changes the loop variable. The change should be such that the condition will eventually become false so the loop will terminate. The modification is performed during each iteration after the body is executed. Notice that the last part (modification) is not following by a semicolon; semicolons are used strictly to separate the three parts.
  • The statement is like the body of any other loop. It may be a compound statement within curly braces.

Flow Diagram

    for-loop in c++ language

Example

      using namespace std;
      int main()
      {
        double rate = 1.15; // Exchange rate:
        // one Euro to one Dollar
        cout << fixed << setprecision(2);
        cout << "\tEuro \tDollar\n";
        for( int euro = 1; euro <= 5; ++euro)
        {
          cout << "\t " << euro  << "\t " << euro*rate << endl;
        }
        return 0;
      }
    

Output

    Euro   Dollar
    1       0.95
    2       1.90
    3       2.85
    4       3.80
    5       4.75