C Programming Tutorial - ITDeveloper

ITDeveloper : C Programming

C Programming

Step by Step Tutorials


Share with a Friend

do...while Loop in C

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop.

do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.

Syntax

The syntax of a do...while loop in C programming language is −

do {   statement(s);} while( condition );

It is to be noted that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false.

Steps:

  • The body of ..whileloop is executed once. Only then, the condition is evaluated.
  • If conditionis true, the body of the loop is executed again and condition is evaluated once more.
  • This process goes on until conditionbecomes false.
  • If conditionis false, the loop ends.

Flowchart of do...while Loop

C do...while loop

Working of do...while loop

Example 1: do...while loop

// Program to add numbers until the user enters zero

#include <stdio.h>

int main()

 {

  int num, sum = 0;

  // the body of the loop is executed at least once

  do {

    printf("Enter a number: ");

    scanf("%d", &num);

    sum += num;

  }

  while(num != 0);

  printf("Sum = %d",sum);

  return 0;

}

OUTPUT:

Enter a number: 5

Enter a number: 10

Enter a number: 15

Enter a number: 20

Enter a number: 25

Enter a number: 0

Sum = 75