Understanding Do While in C Programming

21 May 2023 Balmiki Mandal 0 C Programming

Do While Loops in C Programming

A do while loop is a type of looping structure used in C programming. It is similar to the while loop, but with the order of operations reversed. With a do while loop, the code block is executed first and then the condition is evaluated. If the condition evaluates to true, the loop is re-executed; if it evaluates to false, the loop ends and program flow continues to the following statement.

Do while loops are commonly used when you want to ensure that a task is performed at least once, even if in the end the condition fails. For example, in playing a game, you may want to ask the user to guess a number. Even if the user’s first guess is incorrect, the loop will run over and over until the user guesses correctly.

Syntax of a Do While Loop

The syntax for a do while loop in C programming is as follows:

do {
   // Code to be executed
} while (condition);

In this syntax, the code inside the bracket will be executed at least once. Then, while the given condition (enclosed in parenthesis) resolves to true, the code block will execute again and again.

Example of a Do While Loop in C

Here is an example of a do while loop written in C programming language. The do while loop below calculates the sum of numbers starting from 1 to 10.

#include <stdio.h>

int main() {

   /* Initialize variable sum and set it to 0 */
   int sum = 0;

   /* Initialize variable n and set it to 1 */
   int n = 1;

   /* Execute the code block at least once*/
   do {
      sum = sum + n;
      n++;
   } while (n <= 10);

   printf("Sum of numbers 1 to 10 is %d\n",sum);
   return 0;
}

This code will output:

Sum of numbers 1 to 10 is 55

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.