• Home
  • 5.1 while Loop

5.1 while Loop

View Categories

5.1 while Loop

< 1 min read

Table of Contents

A while loop repeatedly executes a block of statements as long as its controlling condition evaluates to true. The condition is evaluated before each iteration, so the loop body may execute zero or more times depending on the initial condition.

The while loop is useful when the number of iterations is not known in advance and execution should continue while a specific condition remains satisfied.

Source Code #

#include <iostream>

int main()
{
    int count = 1;

    while (count <= 5)
    {
        std::cout << "Count: " << count << '\n';
        ++count;
    }

    return 0;
}

Output #

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

Explanation #

  • while begins a while loop.
  • The condition count <= 5 is evaluated before each iteration.
  • If the condition evaluates to true, the statements inside the loop body are executed.
  • std::cout displays the current value of count.
  • ++count increments count by one after each iteration.
  • When count becomes 6, the condition count <= 5 evaluates to false.
  • The loop terminates and execution continues with the statement following the loop.
  • If the condition is initially false, the loop body is not executed.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

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