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... 





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.