While Loop Without Condition in C
In C, a while
loop without a condition can be implemented using an infinite loop. This is achieved by providing a non-zero value (such as 1
) as the condition. Infinite loops are useful when the program needs to run continuously until an explicit break condition is met.
Examples of While Loops Without Condition
1. Using while(1)
to Create an Infinite Loop
In this example, we will create an infinite loop using while(1)
and print a message continuously. We will terminate the loop when the user enters a specific input.
main.c
</>
Copy
#include <stdio.h>
int main() {
char input;
// Infinite loop using while(1)
while (1) {
printf("Enter 'q' to quit: ");
scanf(" %c", &input);
if (input == 'q') {
break; // Exit the loop when 'q' is entered
}
}
printf("Loop terminated.\n");
return 0;
}
Explanation:
- The
while(1)
loop creates an infinite loop that runs continuously. - The
scanf()
function takes user input and stores it in the variableinput
. - If the user enters
'q'
, theif
statement executesbreak
, which terminates the loop. - After breaking the loop, the program prints “Loop terminated.”
Output:
Enter 'q' to quit: a
Enter 'q' to quit: b
Enter 'q' to quit: q
Loop terminated.
Conclusion
In this tutorial, we explored different ways to create a while
loop without a condition in C.
While loops without conditions are useful in scenarios where continuous execution is needed, such as event-driven programs or embedded systems.