C while Loop
The while
loop in C is a control flow statement that repeatedly executes a block of code as long as a condition is true.
Syntax
while (condition) {
// code block to be executed while condition is true
}
Example
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
return 0;
}
Output
1 2 3 4 5
Explanation
The while
loop in C repeatedly executes a code block as long as the specified condition is true. The condition can be any valid C expression that evaluates to a boolean value (true
or false
).
In the above example, we use a while
loop to print the values of i
from 1 to 5. The while
loop continues to execute the code block as long as i
is less than or equal to 5.
Use
The while
loop is commonly used in C programming for:
- Repeatedly executing a block of code until a certain condition is met.
- Reading input data until a specified sentinel value is encountered.
- Implementing an event loop in computer programs.
Important Points
- The condition specified in a
while
loop is evaluated before each iteration of the loop. - If the condition is initially false, the code inside the loop block is never executed.
- It is important to define a condition in the
while
loop that will eventually become false to avoid infinite loops. - The
while
loop can be replaced with thedo-while
loop if the condition needs to be evaluated at the end of each iteration.
Summary
The while
loop in C is a powerful control flow statement that enables programmers to execute a code block repeatedly as long as a certain condition is true. Understanding the syntax and use cases for while
loops is critical for creating efficient and reliable C programs.