While Loop in C
The while
loop is a flow control structure that allows a block of code to be repeatedly executed as long as a given condition evaluates to true.
The condition is evaluated at the beginning of each iteration of the loop, and if it evaluates to true, the code inside the block is executed. If the condition evaluates to false, the loop is interrupted and the execution of the program continues with the statement following the loop.
- The
while
statement allows a block of code to be repeatedly executed as long as a given condition evaluates to true; - The condition is evaluated at the beginning of each iteration of the loop;
- It is possible that the code inside the loop may never be executed if the condition evaluates to false from the beginning;
- It is important to ensure that the condition is somehow modified inside the loop; otherwise, the loop will become infinite.
while
Statement
The while
statement represents the simplest and most fundamental way to implement a loop in the C language.
In its simplest form, the while
statement has the following syntax:
while ( expression ) statement;
The expression in parentheses represents the control expression, while the statement that follows represents the body of the loop.
Using a flowchart, we can represent the while
statement as follows:
Let’s look at an example:
while (x > y) /* Control expression */
x = x / 2; /* Body of the loop */
The first thing to note is that the parentheses are mandatory and are immediately followed by the body of the loop.
When a while
statement is executed, the control expression is evaluated first. If its value is nonzero, hence true, the body of the loop is executed and the expression is evaluated again. This process continues in this manner—first evaluating the expression and then executing the body—until the control expression becomes false, that is, equal to zero.
Let’s consider the following example: this code calculates the smallest power of 3 greater than or equal to a number n
.
1 2 3 4 |
|
Let’s examine what happens in this case if the variable n
is 30. We execute the code step by step:
- Line 1: the number 1 is assigned to the variable
p
; - Line 2: the expression
p <= n
is true since; - Line 3:
p
is assigned the valuep * 3
, i.e.,; - Line 2: the expression
p <= n
is true since; - Line 3:
p
is assigned the valuep * 3
, i.e.,; - Line 2: the expression
p <= n
is true since; - Line 3:
p
is assigned the valuep * 3
, i.e.,; - Line 2: the expression
p <= n
is true since; - Line 3:
p
is assigned the valuep * 3
, i.e.,; - Line 2: the expression
p <= n
is false since; - Line 4: the loop exits and the statement
printf("%d\n", p);
is executed. Thus, the value81
is printed on the screen.
Note how the loop continues to execute as long as the control expression p <= n
is true. When the expression becomes false, the loop ends, and the value of p
is greater than or equal to n
as required by the program specification.
The example above can be represented with a flowchart as follows:
Even though the body of the loop must be a single statement, we can always construct loops with more than one statement by using compound statements and enclosing the statements within curly braces. For example, we can write code like this:
while (x > n) {
printf("%d\n", x);
x--;
}
It is often common to use curly braces even for loop bodies consisting of a single statement when it would not be necessary, for example:
while (p < n) {
p = p * 3;
}
To recap:
while
Statement
Using the while
statement, it is possible to implement iterative loops in the C language. The general syntax is as follows:
while ( condition ) statement;
As long as the condition condition
is true, the statement statement
will be executed. When the condition condition
becomes false, the loop terminates.
Observations on the while
Statement
Let’s start with an example to make some observations about the while
statement.
Suppose we want to implement a program that prints a countdown starting from 10. We can implement the program as follows:
1 2 3 4 5 6 7 8 9 10 11 |
|
If we try to compile and run this program, we get the following output:
10
9
8
7
6
5
4
3
2
1
Liftoff!
Before the while
statement is executed, the variable n
is assigned the value 10
at line 4. Then, at line 5, the condition is evaluated and it turns out to be true, since 10
is greater than n
, and then line 7 is executed, which decrements n
. The condition is evaluated again—now n
equals n
is zero, the condition becomes false, and the loop terminates.
The first observation to make is the following:
The control condition of a while
statement is false when the loop exits.
It may seem obvious, but it is a fundamental property of while
loops. When a while
loop exits, the condition is always false—otherwise, the program would remain inside the loop.
This happens as long as no statements are used that interrupt the loop, such as break
, return
, or goto
. We will see how to use these statements in the upcoming lessons.
Returning to the example, when the program reaches line 9, the condition n > 0
must necessarily be false, otherwise the loop would continue executing.
The second observation to make is the following:
The body of a while
loop may never be executed.
Since the control expression is evaluated before the loop is executed, it may happen that the body of the loop is not executed even once. This occurs if the condition is already false before the while
statement is executed for the first time.
Returning to the previous example, if instead of assigning the value 10 to the variable n
we had assigned the value -1
, by the time we reach line 5 the condition would already be false, and lines 6 and 7 would not be executed.
For example, modifying the program as follows:
1 2 3 4 5 6 7 8 9 10 11 |
|
The result we get is the following:
Liftoff!
Finally, the last and most important observation about while
loops is the following:
Inside a while
loop, you must include one or more statements that affect the condition.
If a while
loop lacks statements that modify the control condition, the result is that the while
loop never ends. What you get is an infinite loop.
Although this behavior is sometimes intentional, as we’ll see in the next section, it is good practice to never forget to include statements that modify the control condition.
Infinite Loops
If the control expression of a while
statement never evaluates to a nonzero value, the loop never ends. In the C language, an infinite loop is often deliberately constructed by using a nonzero constant as the control expression:
/* Infinite loop */
while (1) {
/* ... */
}
A while
loop written in this way will run indefinitely unless it contains statements (such as break
, return
, or goto
) that transfer the flow of control outside the loop, or if it calls functions that terminate the program. In the upcoming lessons, we will see how to exit from an infinite loop.
There are some situations where using an infinite while
loop—that is, a loop that executes repeatedly without ever stopping—can be useful. Here are some examples of when an infinite loop may be appropriate:
- When you want to create a program that keeps running continuously, for example a program that constantly monitors user input or a server that continuously accepts connection requests.
- More generally, when you want to develop a program that must react to external events or monitor and measure external phenomena. For example, a program in a measurement system.
An example of a "program" that uses infinite loops is an operating system. An operating system waits for external events such as user input or hardware signals and performs tasks in response. Once these tasks are completed, the operating system waits again until it receives notification of more events. Only upon an explicit shutdown request does an operating system end its operations and exit the infinite loop.
In the next lessons, we will see how it is possible to exit a loop.
Summary
In this lesson, we studied the while
statement and saw how to use it to implement loops.
The while
statement evaluates a condition at the beginning of each iteration and:
- if the condition is true, it executes the statements inside the loop;
- if the condition is false, it proceeds to the statement immediately following the loop.
Because of these characteristics, it may happen that the body of a while
loop is never executed. This occurs when the condition is false even before the first iteration. Conversely, the opposite situation may occur: the loop may never terminate if the condition is always true, resulting in an infinite loop.
In the upcoming lessons, we will see how to create loops using different statements of the C language.