Home »
C programming language
How to use for loop as infinite loop in C programming language?
Learn: How we can use a for loop as an infinite to hold (hang) the program or execute set of statements infinitely?
Most of the places while (1) is used as an infinite loop. A for loop can also be used as an infinite loop.
1) for loop as an infinite loop to hold execution
When, we need to hold execution of program (or hang the program), we can use the for loop as an infinite loop.
for(;1;);
Consider the program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("start...\n");
fflush(stdout);
for(;1;);
//program's execution will never reach here...
printf("stop...\n");
return 0;
}
Output
start...
Don’t forget to use semicolon (;) after the loop statement .
2) for loop as an infinite loop to execute statement infinitely
When, we need to execute some set of statements infinitely, we can also use the for loop as an infinite loop.
for(;1;)
{
//statements...
}
Consider the program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("start...\n");
fflush(stdout);
for(;1;)
{
printf("Okay... ");
fflush(stdout);
}
//program's execution will never reach here...
printf("stop...\n");
return 0;
}
Output
start...
Okay... Okay... Okay... Okay... Okay... Okay... Okay... Okay... Okay... Okay...
Okay... Okay... Okay... Okay... Okay... Okay... Okay... Okay... Okay... Okay...
Okay... Okay... Okay... Okay... Okay... Okay... Okay... Okay... Okay... Okay...
Okay... Okay... Okay... Okay... Okay...