Loops in C

A loop repeats a block of code. C provides for, while and do-while loops. The loop should have a clear condition and, for most loops, a way to change that condition.

Syntax / Basic Pattern

for (initialization; condition; update) {
// repeated code
}

 

Easy points to remember

  • for is convenient when the number of repetitions is known.
  • while is useful when repetition depends on a condition.
  • do-while always executes its body at least once.
⭐ 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(){for(int i=1;i<=5;i++) printf(“%d “,i);return 0;}

 

OUTPUT
1 2 3 4 5

 

Program 2: Print 5 to 1

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

 

OUTPUT
5 4 3 2 1

 

Program 3: Sum 1 to 10

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

 

OUTPUT
Sum=55

 

Program 4: Even 1 to 10

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

 

OUTPUT
2 4 6 8 10

 

Program 5: Odd 1 to 10

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

 

OUTPUT
1 3 5 7 9

 

Program 6: Squares

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

 

OUTPUT
1 4 9 16 25

 

Program 7: Cubes

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

 

OUTPUT
1 8 27 64

 

Program 8: Multiples of 3

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

 

OUTPUT
3 6 9 12 15

 

Program 9: Count down

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

 

OUTPUT
5 4 3 2 1

 

Program 10: Sum even

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

 

OUTPUT
110

 

Program 11: Factorial

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

 

OUTPUT
120

 

Program 12: Power

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

 

OUTPUT
32

 

Program 13: Table of 7

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

 

OUTPUT
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

 

Program 14: Count digits

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

 

OUTPUT
Digits=4

 

Program 15: Reverse number

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

 

OUTPUT
4321
Scroll to Top