Do While Loop in C Programming with Example

Do while loop in c programming; In this tutorial, i am going to show you what is do while loop and how to use do while loop in C programming with c program examples.

Do While Loop in C Programming with Example

Here, i will teach you do while loop in c programming with examples; is as follows:

  • Do While loop in c
  • Syntax of do while loop in c
  • Example 1 – C Do while loop Program Example
  • Example 2 – C program to reverse a number using do while loop

Do While loop in c

The c do..while loop is similar to the while loop with one exception. The body of do...while loop is executed at least once. Only then, the test expression is evaluated.

In other words, The C do while loop executes the first body of code. Then evaluates to test expression.

Syntax of do while loop in c

The syntax of the C do...while loop is:

do
{
    //Statements 

}while(condition test);

Illustration of above given c do while loop syntax

  • The body of code executed first. Then, the testExpression is evaluated.
  • If testExpression is true, the body of the loop is executed again and testExpression is evaluated once more.
  • This process continues until TestExpression is found to be false.
  • If testExpression is false, the loop terminate.

Example 1 – C Do while loop Program Example

Let’s create simple program in c using do while loop; as shown below:

// Program to add numbers until the user enters zero
#include <stdio.h>
int main() {
  double number, sum = 0;
  // the body of the loop is executed at least once
  do {
    printf("Enter a number: ");
    scanf("%lf", &number);
    sum += number;
  }
  while(number != 0.0);
  printf("Sum = %.2lf",sum);
  return 0;
}

Output

Enter a number: 10
Enter a number: 1
Enter a number: 4
Enter a number: 4
0Enter a number: 0
Sum = 19.00

Example 2 – C program to reverse a number using do while loop

Let’s create c program to reverse a number using do while loop; as shown below:

#include <stdio.h>
int main()
{
    int num = 123;
    int reverse=0,rem;
 
    printf("You number is 123 \n");
    do{
        rem=num%10;
        reverse=reverse*10+rem;
        num/=10;
    }while(num!=0);
    printf("Reverse number is %d\n",reverse);
  
    return 0;
}

Output

You number is 123 
Reverse number is 321

More C Programming Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.