Looping with while
In C programming, the `while` loop allows you to repeatedly execute a block of code as long as a specified condition is true. It's a pre-test loop, meaning the condition is evaluated before each iteration.
The basic syntax of the `while` loop in C is as follows:
while (condition) {
// code to execute
}
The `condition` is an expression that evaluates to either true or false. If the condition is true, the code block within the while loop will be executed. After each iteration, the condition is re-evaluated. If the condition is still true, the loop continues to execute. If the condition becomes false, the loop is exited, and the program continues with the statement after the while loop.
Here's an example to illustrate the usage of `while` loop:
#include <stdio.h>
int main() {
int count = 1;
while (count <= 5) {
printf("Count: %d\n", count);
count++;
}
printf("Loop complete.\n");
return 0;
}
In this example, the program initializes a variable `count` with the value 1. The while loop executes as long as `count` is less than or equal to 5. Within each iteration, it prints the value of `count` and increments it by 1 using `count++`. Once `count` becomes 6, the condition `count <= 5` becomes false, and the loop is exited. The output will be the numbers 1 to 5 printed on separate lines.
It's important to ensure that the condition specified in the `while` loop will eventually become false to avoid infinite loops. Without a proper terminating condition or a mechanism to change the condition within the loop, it can lead to an infinite loop, causing the program to run indefinitely.
You can also use the `break` statement within the while loop to exit the loop prematurely based on certain conditions. For example:
#include <stdio.h>
int main() {
int num = 1;
while (1) {
printf("Number: %d\n", num);
num++;
if (num > 10) {
break;
}
}
printf("Loop complete.\n");
return 0;
}
In this example, the while loop is an infinite loop (condition `1` is always true). However, the `if` statement within the loop checks if `num` is greater than 10, and if so, it uses the `break` statement to exit the loop.
The `while` loop is useful when you want to repeat a block of code until a certain condition is met. It's important to update the variables involved in the condition appropriately within the loop to prevent infinite looping.