Definition: The while loop is an entry-controlled loop that repeatedly executes a block of statements as long as the given condition remains true.
Definition: The while loop is an
entry-controlled loop that repeatedly executes a
block of statements as long as the given condition remains true.
i <= 5, the loop can print the numbers from
1 to 5. The condition is checked before every iteration.
while (condition)
{
statements;
}
To print numbers from 1 to 5, initialize i to 1 and
continue the loop while i <= 5.
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d ", i);
i++; // move to the next number
}
return 0;
}
1 2 3 4 5
A while loop checks its condition before
executing the loop body. Therefore, if the condition is false at the
beginning, the loop body will not execute.
i = 10 and the condition is
i <= 5, the condition is false initially, so nothing
inside the loop is executed.
A program may continue asking for information while a particular condition is true. For example, a system can keep processing items while items are still available.
Write a C program to print all integers from 1 to N
using a while loop.
while loop.
Initialize the counter to 1, print it, and increment it
until it becomes greater than N.
A while loop checks its condition before each iteration.
If the condition is true, the loop body executes; otherwise, the loop
ends.
#include <stdio.h>
int main()
{
int n, i = 1; // i is the loop counter, starting at 1
printf("Enter N: ");
scanf("%d", &n);
while (i <= n) // repeat while i has not exceeded n
{
printf("%d ", i);
i++; // move to the next number
}
printf("
");
return 0;
}
Enter N: 10 1 2 3 4 5 6 7 8 9 10
A common mistake is forgetting to update the loop variable.
For example, forgetting i++ can create an
infinite loop because the condition may never become
false.
| while | if |
|---|---|
| Used for repeated execution. | Used for decision making. |
| May execute many times. | Normally executes at most once. |
| Condition is checked before every iteration. | Condition is checked once when the statement is reached. |
while is an entry-controlled loop.Watch a beginner-friendly explanation of the while loop in C.
A short handwritten-style revision sheet for the while loop will be provided here.
Use the mind map for quick revision of initialization, condition, execution and update.