Infinite Loop in C
An infinite loop is a loop that does not naturally stop because its condition remains true. It can be intentional, such as a server/menu loop, but an accidental infinite loop is usually a bug.
Syntax / Basic Pattern
| while (1) { /* stop using break when required */ } |
Easy points to remember
- Use a clear exit condition when possible.
- break can be used to stop an intentional infinite loop.
- Always test infinite loops carefully so the program can exit.
| ⭐ PRACTICE TIP: Type these programs yourself. Change the values and run them again. That is how control statements become easy. |
Program 1: while(1) with break
| #include <stdio.h> int main(){int i=1;while(1){printf(“%d “,i);if(i==3)break;i++;}return 0;} |
| OUTPUT 1 2 3 |
Program 2: for(;;) with break
| #include <stdio.h> int main(){int i=1;for(;;){printf(“%d “,i);if(i==4)break;i++;}return 0;} |
| OUTPUT 1 2 3 4 |
Program 3: Menu-style loop
| #include <stdio.h> int main(){int choice=2;while(1){printf(“Choice=%d”,choice);if(choice==2)break;}return 0;} |
| OUTPUT Choice=2 |
Program 4: Countdown
| #include <stdio.h> int main(){int i=5;while(1){printf(“%d “,i);if(i==1)break;i–;}return 0;} |
| OUTPUT 5 4 3 2 1 |
Program 5: Find first multiple
| #include <stdio.h> int main(){int i=1;while(1){if(i%7==0){printf(“%d”,i);break;}i++;}return 0;} |
| OUTPUT 7 |
Program 6: Find square
| #include <stdio.h> int main(){int i=1;while(1){if(i*i>=30){printf(“%d”,i*i);break;}i++;}return 0;} |
| OUTPUT 36 |
Program 7: Sum until 5
| #include <stdio.h> int main(){int i=1,s=0;for(;;){s+=i;if(i==5)break;i++;}printf(“%d”,s);return 0;} |
| OUTPUT 15 |
Program 8: Print even then stop
| #include <stdio.h> int main(){int i=2;while(1){printf(“%d “,i);if(i==8)break;i+=2;}return 0;} |
| OUTPUT 2 4 6 8 |
Program 9: Power until >=100
| #include <stdio.h> int main(){int p=1;while(1){p*=2;if(p>=100)break;}printf(“%d”,p);return 0;} |
| OUTPUT 128 |
Program 10: Search digit
| #include <stdio.h> int main(){int n=4826,d;while(1){d=n%10;if(d==8){printf(“Found 8”);break;}n/=10;if(n==0){printf(“Not found”);break;}}return 0;} |
| OUTPUT Found 8 |
Program 11: Stop at 0
| #include <stdio.h> int main(){int a[]={4,3,0,9},i=0;while(1){if(a[i]==0)break;printf(“%d “,a[i]);i++;}return 0;} |
| OUTPUT 4 3 |
Program 12: Prime-like test
| #include <stdio.h> int main(){int n=29,i=2,prime=1;while(1){if(i*i>n)break;if(n%i==0){prime=0;break;}i++;}printf(“%s”,prime?”Prime”:”Not prime”);return 0;} |
| OUTPUT Prime |
Program 13: Fibonacci stop
| #include <stdio.h> int main(){int a=0,b=1,c;while(1){printf(“%d “,a);if(a>=10)break;c=a+b;a=b;b=c;}return 0;} |
| OUTPUT 0 1 1 2 3 5 8 13 |
Program 14: Attempts
| #include <stdio.h> int main(){int attempts=0;while(1){attempts++;if(attempts==3)break;}printf(“Attempts=%d”,attempts);return 0;} |
| OUTPUT Attempts=3 |
Program 15: Infinite loop concept
| #include <stdio.h> int main(){int i=1;for(;;){if(i>2)break;printf(“Run%d “,i);i++;}return 0;} |
| OUTPUT Run1 Run2 |
