• Home
  • 2.11 while Loop

2.11 while Loop

View Categories

2.11 while Loop

< 1 min read

Table of Contents

The while loop repeatedly executes a block of code as long as its condition evaluates to a non-zero value.

#include <stdio.h>

int main()
{
    int i = 1;

    while (i <= 5)
    {
        printf("%d\n", i);
        i++;
    }

    return 0;
}

Example Output #

1
2
3
4
5

Explanation #

The condition is evaluated before each iteration:

while (i <= 5)

As long as the condition is non-zero, the loop body executes.

The value of i is incremented after each iteration:

i++;

When i becomes 6, the condition i <= 5 evaluates to 0, so the loop terminates.

Because the condition is checked before the loop body, a while loop can execute zero times if its initial condition is false.

Powered by BetterDocs

Leave a Reply

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