BM Balmiki Mandal 21 May 2023 15 views 0 comments C Programming

Understanding Do While in 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

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

C Bitwise Operators Explained: 10 Practice Programs with Output

E.1: Bitwise vs. Logical Operators#include<stdio.h> int main(void){ int x=7,y=19; printf("%d %d ",x&y...

AG Anvesh G 29 Nov 2026
Bit wise operators Assignment

Bitwise Operators practical assignment: Take runtime input, bit-level manipulation, and different data units r...

AG Anvesh G 27 Sep 2026
Understanding Float and Double Binary Representation in C

Understanding Float and Double Binary Representation in CIntroduction:When we store decimal numbers such as 10...

AG Anvesh G 31 May 2026