While loop in C

A while loop checks its condition before each repetition. If the condition is false at the beginning, the body may execute zero times.

Syntax / Basic Pattern

while (condition) {
// body
}

 

Easy points to remember

  • Initialize the control variable before the loop.
  • Change the control variable inside the loop when required.
  • Use while when the number of repetitions is not necessarily known in advance.
⭐ 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;while(i<=5){printf(“%d “,i);i++;}return 0;}

 

OUTPUT
1 2 3 4 5

 

Program 2: Print 5 to 1

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

 

OUTPUT
5 4 3 2 1

 

Program 3: Sum 1 to 10

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

 

OUTPUT
55

 

Program 4: Even numbers

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

 

OUTPUT
2 4 6 8 10

 

Program 5: Odd numbers

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

 

OUTPUT
1 3 5 7 9

 

Program 6: Table

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

 

OUTPUT
7 14 21 28 35 42 49 56 63 70

 

Program 7: Factorial

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

 

OUTPUT
120

 

Program 8: Count digits

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

 

OUTPUT
4

 

Program 9: Reverse

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

 

OUTPUT
654

 

Program 10: Sum digits

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

 

OUTPUT
19

 

Program 11: Power

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

 

OUTPUT
16

 

Program 12: Squares

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

 

OUTPUT
1 4 9 16 25

 

Program 13: Multiples of 6

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

 

OUTPUT
6 12 18 24 30

 

Program 14: Count down by 2

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

 

OUTPUT
10 8 6 4 2

 

Program 15: Find first multiple

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

 

OUTPUT
9
Scroll to Top