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.

</>
Copy
while (1) {
    // Code to execute indefinitely
}

Explanation of Syntax:

  1. The condition inside the while loop is always 1, which means it is always true.
  2. The loop body executes continuously until it is interrupted manually (e.g., using Ctrl + C) or a break statement.

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

</>
Copy
#include <stdio.h>

int main() {
    while (1) {
        printf("This loop runs forever!\n");
    }
    return 0;
}

Explanation:

  1. The while loop condition is always 1, making it an infinite loop.
  2. Inside the loop, printf() prints the message continuously.
  3. To stop the program, press Ctrl + C in 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

</>
Copy
#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:

  1. The loop runs infinitely with while (1).
  2. A counter variable count is incremented in each iteration.
  3. When count reaches 5, the break statement stops the loop.
  4. 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:

  1. The syntax of infinite while loops.
  2. An example of an infinite loop that prints a message continuously.
  3. How to use the break statement to exit an infinite loop.

Infinite loops are useful for continuous operations, but they must be controlled carefully to prevent unintended behavior.