The while loop in the C programming language allows you to execute a block of code repeatedly as long as a specified condition is true. It's useful when you want to repeat a block of code an unknown number of times until a certain condition is met.
Here's the basic syntax of a while loop in C:
while (condition) {
// code to be executed as long as the condition is true
}
Here's a breakdown of each part:
while
: This is the keyword that indicates the start of the while
loop.condition
: This is an expression that is evaluated before each iteration of the loop. If the condition evaluates to true, the code inside the loop is executed. If it evaluates to false, the loop terminates.Here's a simple example of using a while loop to print numbers from 1 to 5:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
In this example, the loop will continue executing as long as the value of i
is less than or equal to 5. Inside the loop, printf
prints the value of i
, and then i
is incremented by 1 in each iteration. So, it will print:
1
2
3
4
5
The loop terminates when i
becomes 6, as the condition i <= 5
is no longer true.