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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.