While Loop
While Loop
A while loop in C is a control flow statement that allows code to be executed repeatedly based
on a given condition. The while loop keeps executing as long as the condition remains true.
When the condition becomes false, the loop stops.
while (condition) {
// Statements inside the loop
}
Here is a simple example that prints numbers from 1 to 5 using a while loop
int main() {
int i = 1;
return 0;
}
Output:
1
2
3
4
5
How It Works:
Key Points:
● If the condition is initially false, the loop body won't be executed even once.
● You must ensure that the loop condition eventually becomes false, or you will get an
infinite loop.
If the condition never becomes false, the loop will run indefinitely, causing an infinite loop.
#include <stdio.h>
int main() {
int i = 1;
return 0;
}
This will keep printing 1 indefinitely because i is not being incremented, so the condition i <=
5 is always true.
Common Use Cases of while Loop:
Reading input until a specific condition is met:
int num;
printf("Enter numbers (enter -1 to stop): ");
scanf("%d", &num);
This loop continues taking input until the user enters -1.
int sum = 0, i = 1;
The loop runs until i exceeds 10, calculating the sum of numbers from 1 to 10.