The while loop is a fundamental control structure in C programming. It allows you to execute a block of code repeatedly as long as a specified condition remains true.
The basic syntax of a while loop in C is:
while (condition) {
// code to be executed
}
The while loop operates as follows:
Here's a simple example that counts from 1 to 5:
#include <stdio.h>
int main() {
int count = 1;
while (count <= 5) {
printf("%d ", count);
count++;
}
return 0;
}
Output: 1 2 3 4 5
This example demonstrates using a while loop for user input validation:
#include <stdio.h>
int main() {
int number;
while (1) {
printf("Enter a positive number: ");
scanf("%d", &number);
if (number > 0) {
break;
}
printf("Invalid input. Try again.\n");
}
printf("You entered: %d\n", number);
return 0;
}
While loops are particularly useful when:
To further enhance your understanding of loops in C, explore these related topics:
Mastering while loops is crucial for effective C programming. They provide flexibility in controlling program flow and are essential for tasks requiring repetition based on dynamic conditions.