Infinite While Loop in C
An infinite while loop in C is a loop that never terminates because the condition always evaluates to true. Infinite loops are commonly used in applications like server processes, real-time monitoring systems, and embedded programming.
In this tutorial, you will learn how infinite while loops work in C, their syntax, and examples of their usage.
Syntax of the Infinite While Loop
To create an infinite loop, we use a while loop with a condition that always evaluates to true.
while (1) {
    // Code to execute indefinitely
}Explanation of Syntax:
- The condition inside the whileloop is always1, which means it is alwaystrue.
- The loop body executes continuously until it is interrupted manually (e.g., using Ctrl + C) or abreakstatement.
Examples of Infinite While Loop
1 Printing a Message Continuously using Infinite While Loop
In this example, we use an infinite while loop to print a message repeatedly.
main.c
#include <stdio.h>
int main() {
    while (1) {
        printf("This loop runs forever!\n");
    }
    return 0;
}Explanation:
- The whileloop condition is always1, making it an infinite loop.
- Inside the loop, printf()prints the message continuously.
- To stop the program, press Ctrl + Cin the terminal.
Output:
This loop runs forever!
This loop runs forever!
This loop runs forever!
...
2 Using break to Exit an Infinite Loop
We can use the break statement to exit an infinite loop under a specific condition.
main.c
#include <stdio.h>
int main() {
    int count = 1;
    
    while (1) {
        printf("Iteration %d\n", count);
        
        if (count == 5) {
            break; // Exit the loop when count reaches 5
        }
        
        count++;
    }
    printf("Loop exited.\n");
    return 0;
}Explanation:
- The loop runs infinitely with while (1).
- A counter variable countis incremented in each iteration.
- When countreaches5, thebreakstatement stops the loop.
- After the loop exits, printf()prints “Loop exited.”
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Loop exited.Conclusion
In this tutorial, we explored infinite while loops in C, including:
- The syntax of infinite whileloops.
- An example of an infinite loop that prints a message continuously.
- How to use the breakstatement to exit an infinite loop.
Infinite loops are useful for continuous operations, but they must be controlled carefully to prevent unintended behavior.
