How Useful "while" Can Be Sometimes!
Previously, with the
for statement, we knew the exact number of steps (exactly
4 iterations,
the number of colors in the list). Let's consider another example.
A car runs as long as there is fuel in the tank, right? We never know precisely how many more kilometers we can travel.
In this situation,
the number of iterations is unknown.
If we run out of fuel, the engine
stops immediately...
With the help of the
while statement, we can simulate processes such as
"
as long as a logical condition is true, execute a series of instructions..."
EXAMPLE
A natural number
n, different from
0, is read. Print the
sum of its digits.
HOW DO WE READ THIS?
As long as the condition is true, execute the subordinate instructions!
DETAILS ABOUT THE ALGORITHM
This problem has been solved before, but in that case, we knew the number of digits the number had from the beginning.
How do we proceed now when we don't know this?
There could be
3,
4,
5, or
10 digits, depending on the
user!
We isolate the last digit (which we add to a variable
sum, initially set to
0), then obtain the number without the last digit.
These operations are performed
repetitively, as long as the number is not
0.
When it is equal to
0, there is nothing left to process, right? Consequently, the
while loop stops.
Let's continue to play a bit with these two statements!
Proceed to the next page.