Do-while loop in C

A do-while loop executes the body first and checks the condition afterward. Therefore, the body runs at least one time.

Syntax / Basic Pattern

do {
// body
} while (condition);

 

Easy points to remember

  • There is a semicolon after while(condition).
  • Useful for menus and input that must be shown at least once.
  • Update the control variable to avoid an unintended infinite loop.
⭐ PRACTICE TIP: Type these programs yourself. Change the values and run them again. That is how control statements become easy.

 

Program 1: Print 1 to 5

#include <stdio.h>
int main(){int i=1;do{printf(“%d “,i);i++;}while(i<=5);return 0;}

 

OUTPUT
1 2 3 4 5

 

Program 2: Print 5 to 1

#include <stdio.h>
int main(){int i=5;do{printf(“%d “,i);i–;}while(i>=1);return 0;}

 

OUTPUT
5 4 3 2 1

 

Program 3: Sum 1 to 5

#include <stdio.h>
int main(){int i=1,s=0;do{s+=i;i++;}while(i<=5);printf(“Sum=%d”,s);return 0;}

 

OUTPUT
Sum=15

 

Program 4: Even numbers

#include <stdio.h>
int main(){int i=2;do{printf(“%d “,i);i+=2;}while(i<=10);return 0;}

 

OUTPUT
2 4 6 8 10

 

Program 5: Odd numbers

#include <stdio.h>
int main(){int i=1;do{printf(“%d “,i);i+=2;}while(i<=9);return 0;}

 

OUTPUT
1 3 5 7 9

 

Program 6: Table of 5

#include <stdio.h>
int main(){int i=1;do{printf(“%d “,5*i);i++;}while(i<=10);return 0;}

 

OUTPUT
5 10 15 20 25 30 35 40 45 50

 

Program 7: Factorial

#include <stdio.h>
int main(){int n=5,i=1,f=1;do{f*=i;i++;}while(i<=n);printf(“%d”,f);return 0;}

 

OUTPUT
120

 

Program 8: Count digits

#include <stdio.h>
int main(){int n=9042,c=0;do{c++;n/=10;}while(n!=0);printf(“%d”,c);return 0;}

 

OUTPUT
4

 

Program 9: Reverse

#include <stdio.h>
int main(){int n=321,r=0;do{r=r*10+n%10;n/=10;}while(n);printf(“%d”,r);return 0;}

 

OUTPUT
123

 

Program 10: Sum digits

#include <stdio.h>
int main(){int n=582,s=0;do{s+=n%10;n/=10;}while(n);printf(“%d”,s);return 0;}

 

OUTPUT
15

 

Program 11: Menu once

#include <stdio.h>
int main(){int choice=2;do{printf(“Menu shown; choice=%d”,choice);break;}while(choice!=0);return 0;}

 

OUTPUT
Menu shown; choice=2

 

Program 12: Power

#include <stdio.h>
int main(){int b=3,e=4,p=1,i=1;do{p*=b;i++;}while(i<=e);printf(“%d”,p);return 0;}

 

OUTPUT
81

 

Program 13: Squares

#include <stdio.h>
int main(){int i=1;do{printf(“%d “,i*i);i++;}while(i<=5);return 0;}

 

OUTPUT
1 4 9 16 25

 

Program 14: Multiples of 4

#include <stdio.h>
int main(){int i=4;do{printf(“%d “,i);i+=4;}while(i<=20);return 0;}

 

OUTPUT
4 8 12 16 20

 

Program 15: At least one execution

#include <stdio.h>
int main(){int i=10;do{printf(“Runs once”);i++;}while(i<5);return 0;}

 

OUTPUT
Runs once
Scroll to Top