What is a while Loop?
A while
loop is a control flow statement in programming that allows a block of code to be executed repeatedly as long as a certain condition is true. The while
loop is one of the most fundamental control structures in programming, and it is used extensively in various programming languages, including C.
The general syntax of a while
loop in C is as follows:
while (condition) {
// code block to be executed
}
Here's how the while
loop works:
- The
condition
is evaluated first. If the condition is true, the code block inside the loop is executed. - After the code block is executed, the
condition
is evaluated again. - If the
condition
is still true, the code block is executed again. - This process continues until the
condition
becomes false, at which point the loop terminates, and the program continues with the next statement outside the loop.
Here's an example of a while
loop in C that prints the 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 condition
is i <= 5
, which means the loop will continue as long as the value of i
is less than or equal to 5. Inside the loop, the printf()
function is used to print the current value of i
, and then i
is incremented by 1 using the i++
statement.
The output of this program will be:
1
2
3
4
5
The while
loop is a powerful control structure that allows you to create complex and flexible programs. It is often used in situations where the number of iterations is not known in advance, or where the loop needs to continue until a certain condition is met.
Here's a Mermaid diagram that illustrates the flow of a while
loop:
In the diagram, the while
loop starts with evaluating the condition. If the condition is true, the code block inside the loop is executed. After the code block is executed, the condition is evaluated again. This process continues until the condition becomes false, at which point the loop terminates.
The while
loop is a versatile and essential control structure in programming, and understanding how it works is crucial for writing efficient and effective C programs.