While Loops
Lesson 22Author : Afrixi
Last Updated : January, 2023
A while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. Here’s an example of a while loop in C:
#include <stdio.h>
int main() {
int count = 0;
while (count < 5) {
printf("Count is %d\n", count);
count++;
}
return 0;
}
In this example, we have a while loop that runs as long as the count
variable is less than 5. Inside the loop, we print out the value of count using printf()
and then increment count
by 1 using the ++
operator.
Here’s how the loop works:
- First, we initialize the
count
variable to 0. - Next, we start the while loop. Since
count
is currently 0, the condition (count < 5
) is true, so we enter the loop. - Inside the loop, we print out “Count is 0” using
printf()
. - We then increment
count
by 1 using the++
operator, socount
is now 1. - Since
count
is still less than 5, we go back to the top of the loop and repeat steps 3-4 with the new value ofcount
. - We repeat this process until
count
is no longer less than 5. At this point, the condition (count < 5
) is false, so we exit the loop and continue with the rest of the program.
While loops are useful for situations where you need to repeat a block of code an unknown number of times, depending on some condition. They can be a bit tricky to get right, since you need to make sure the condition eventually becomes false to avoid an infinite loop.