c
  1. c-do-while-loop

C do-while Loop

Syntax

do {
  // code block
} while (condition);

Example

#include <stdio.h>

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

Output

Output of the above code will be:

0
1
2
3
4

Explanation

The do-while loop in C is a control statement that executes a block of code followed by a condition check. The code block will execute at least once, even if the condition is not initially met. Once the code block has been executed, the condition is checked. If the condition is true, the code block will be executed again, and the process will continue until the condition is false.

Use

The do-while loop is useful for executing a block of code at least once, such as validating user input and prompting the user to try again if invalid input is entered. It can also be used to process data in a sequential or iterative manner.

Important Points

  • The do-while loop differs from the while loop in that the code block is executed at least once before the condition is checked.
  • The do-while loop can be useful for user input validation and processing data in a sequential or iterative manner.
  • The braces {} are used to enclose the code block in a do-while loop.

Summary

The do-while loop in C is a powerful control statement that allows a block of code to be executed at least once before the loop condition is checked. This is useful for input validation, as well as processing data in a sequential or iterative manner. Understanding the syntax and use cases for the do-while loop is a fundamental skill for any C programmer.

Published on: