• Home
  • 2.12 do-while Loop

2.12 do-while Loop

View Categories

2.12 do-while Loop

< 1 min read

Table of Contents

The do-while loop executes its block once before checking the condition. After each iteration, the condition is evaluated to determine whether another iteration should occur.

#include <stdio.h>

int main()
{
    int i = 1;

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

    return 0;
}

Example Output #

1
2
3
4
5

Explanation #

The loop body executes before the condition is evaluated:

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

After the first iteration, i is incremented and the condition is checked:

while (i <= 5);

The loop continues while the condition evaluates to a non-zero value.

Unlike a while loop, a do-while loop always executes its body at least once, even when the condition is initially false.

The semicolon after the while condition is required.

Powered by BetterDocs

Leave a Reply

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