While Statement
The while statement in C is used to create a loop that repeatedly executes a block of code as long as a given condition is true. It's one of the most basic forms of looping in C.
while Syntax
while (condition) {
// Code to execute while the condition is true
}
How It Works:
- The condition is evaluated before each iteration.
- If the condition is true (non-zero), the code inside the loop executes.
- After executing the loop body, the condition is re-evaluated.
- The loop continues until the condition becomes false (zero).
Example:1
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Output
0
1
2
3
4
1
2
3
4
Example 2:Sum of Natural Numbers
#include <stdio.h>
int main() {
int n, sum = 0, i = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
while (i <= n) {
sum += i; // Add i to the sum
i++;
}
printf("The sum of first %d natural numbers is %d\n", n, sum);
return 0;
}
Output
Enter a positive integer: 5
The sum of first 5 natural numbers is 15
Example 3: Infinite Loop
#include <stdio.h>
int main() {
while (1) {
printf("This is an infinite loop.\n");
}
return 0;
}
Output
The loop continues until interrupted manually (e.g., using Ctrl + C).- Condition:
- The condition is checked at the beginning of each iteration.
- If the condition is initially false, the loop body is skipped.
- Infinite Loop:
- Be careful with infinite loops. Ensure there's a mechanism to break out if necessary.
- Variables:
- Use variables within the condition to control the loop (e.g., counters or flags).
- Avoid Common Errors:
- Ensure the condition will eventually become false to prevent unintended infinite loops.