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 #
forbegins aforloop.int count = 1is the initialization expression and is executed once before the first iteration.count <= 5is the loop condition and is evaluated before each iteration.++countis the iteration expression and incrementscountafter each execution of the loop body.- The loop body executes while the condition evaluates to
true. - When
countbecomes6, the conditioncount <= 5evaluates tofalse, and the loop terminates. - The variable
countdeclared in the initialization expression is local to theforloop. - The three expressions in a
forstatement are separated by semicolons. return 0;terminates the program successfully.