c-plus-plus
  1. c-plus-plus-for-loop

C++ Control Statement - For Loop

The for loop is a control statement that allows a block of code to be repeated a fixed number of times. It is also known as a counting loop, as it executes a preset number of iterations, specified by the user.

Syntax:

for (initialization; condition; increment/decrement) {
    // code to be executed repeatedly
}
  • initialization: initializes the loop counter variable
  • condition: specifies the condition for loop termination
  • increment/decrement: updates the loop counter variable after each iteration

Example:

#include <iostream>

using namespace std;

int main() {
    for(int i=1; i<=5; i++) {
        cout << i << " ";
    }
    return 0;
}

Output:

1 2 3 4 5

Explanation:

In the above example, the loop is initialized with i=1. The condition i<=5 specifies that the loop should continue until i is less than or equal to 5. After each iteration, i is incremented by 1 using i++. The output shows the values of i from 1 to 5.

Use:

The for loop is commonly used in programs for iteration and repetition of certain actions. It is used in situations when we know the exact number of times a block of code should be executed.

Important Points:

  • The initialization, condition, and increment/decrement are all optional.
  • The body of the loop can contain any valid C++ statements, including nested loops and other control statements such as if and switch.
  • The break statement can be used to terminate the loop early, while the continue statement can be used to skip a certain iteration.

Summary:

  • The for loop is a control statement that executes a block of code a fixed number of times.
  • It has an initialization, condition, and increment/decrement.
  • It is commonly used in situations when we know the exact number of times a block of code should be executed.
  • Other control statements such as if and switch can be nested within a for loop.
  • The break and continue statements can be used to terminate the loop early or skip a certain iteration.
Published on: