5.3 for Loop

View Categories

5.3 for Loop

1 min read

Table of Contents

A for loop repeatedly executes a block of statements while a specified condition remains true. It combines initialization, condition evaluation, and iteration into a single loop statement, making it particularly suitable when the loop has a clearly defined counter or iteration sequence.

The for loop consists of three expressions: an initialization expression, a condition, and an iteration expression. The initialization is executed once before the loop begins, the condition is evaluated before each iteration, and the iteration expression is evaluated after each execution of the loop body.

Source Code #

#include <iostream>

int main()
{
    for (int count = 1; count <= 5; ++count)
    {
        std::cout << "Count: " << count << '\n';
    }

    return 0;
}

Output #

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Explanation #

  • for begins a for loop.
  • int count = 1 is the initialization expression and is executed once before the first iteration.
  • count <= 5 is the loop condition and is evaluated before each iteration.
  • ++count is the iteration expression and increments count after each execution of the loop body.
  • The loop body executes while the condition evaluates to true.
  • When count becomes 6, the condition count <= 5 evaluates to false, and the loop terminates.
  • The variable count declared in the initialization expression is local to the for loop.
  • The three expressions in a for statement are separated by semicolons.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *