While Loop in C
The while
loop in C is used to repeatedly execute a block of code as long as a specified condition remains true. It is particularly useful when the number of iterations is not known beforehand.
Syntax of While Loop
while (condition) {
// Code to execute while condition is true
}
Example: Counting from 1 to 5
#include <stdio.h>
int main() {
int count = 1;
while (count <= 5) {
printf("Count: %d\n", count);
count++;
}
return 0;
}
Output:
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
Code Explanation: The loop continues as long as count <= 5
is true. The variable count
is incremented in each iteration.
Best Practices
- Ensure that the loop condition will eventually become false to avoid infinite loops.
- Initialize loop variables before entering the loop.
- Keep the loop body concise and focused on a single task.
Don'ts
Key Takeaways
- The
while
loop is useful when the number of iterations is not predetermined. - Proper initialization and updating of the loop variable are crucial.
- Always ensure the loop condition will eventually become false.