do while loop in C

In this lesson, we will be learning about the do-while loop in C with examples. A do-while loop is a form of flow control statement that executes until the condition mentioned is false.

Syntax of the do-while loop in C

do{
  // block of code to be executed 
} while( condition );

Example I of the do-while loop in C

#include <stdio.h>

int main() {
  int i = 0;
  do {
    printf("Hello World\n");
  } while (4 < 1);
  return 0;
}

Output

Hello World

Here we can observe that the statement inside the do block was executed even though the condition is false right from the start. Another example where we can see do-while loops in action is for conditional input taking scenarios.

Example II of the do-while loop in C

// Program to add integers until zero is entered
#include <stdio.h>

int main() {
  int number, sum = 0;

  // the body of the loop is executed at least once
  do {
    printf("Input a number of your choice: ");
    scanf("%d", & number);
    sum += number;
  }
  while (number != 0);

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

  return 0;
}

Enter a number: 1

Enter a number: 52

Enter a number: 13

Enter a number: 4

Enter a number: 0

Sum = 70

 

In the above example, the do-while loop will keep getting executed until the user enters 0, and the “Sum” is represented as the sum of numbers entered before 0.

Summary

  • This loop ensures that the statements within it are executed at least once.
  • There is a slight difference between the do-while loop and while loop. The while loop examines the condition before executing any of the statements within it, whereas the do-while execute the statement then check the condition.

 

Back to: Learn C Programming > Control Statements in C

Leave a Reply

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