The while
loop in C is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. It has the following syntax:
while (condition) { // Code block to be executed while the condition is true }
Here’s an explanation of how the while
loop works:
- Condition Evaluation:
- The loop starts by evaluating the condition inside the parentheses (
()
). - If the condition is true, the code block inside the loop is executed. If the condition is false initially, the loop is skipped entirely, and the program moves to the next statement after the loop.
- The loop starts by evaluating the condition inside the parentheses (
- Execution of Code Block:
- If the condition is true, the code block inside the loop is executed.
- After executing the code block, 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.
- Updating Variables:
- It’s essential to ensure that the loop condition will eventually become false; otherwise, the loop will execute indefinitely, resulting in an infinite loop.
- Typically, the loop condition involves variables that are updated within the loop body to ensure termination.
Now, let’s see an example of a while
loop:
#include <stdio.h> int main() { int count = 1; // Print numbers from 1 to 5 using a while loop while (count <= 5) { printf("%d\n", count); count++; // Increment count by 1 } return 0; }
In this example:
- We initialize a variable
count
to 1. - The
while
loop executes as long as the conditioncount <= 5
is true. - Inside the loop, we print the value of
count
usingprintf
. - We then increment the value of
count
by 1 using thecount++
statement. - After each iteration, the value of
count
increases, and the loop continues untilcount
becomes greater than 5. - Once
count
becomes 6, the conditioncount <= 5
becomes false, and the loop terminates. - The program then proceeds to the next statement after the
while
loop.
Team Edited answer April 13, 2024