The if statement was introduced in the previoussection. In this section, we’ll learn another statement, the while statement.
Let’s start from an example. While Lisa went to work, her baby cried. This
description implies that her baby had cried until Lisa came back. Combining
these two sentences, we got the following statement.
In other words, during the time that the
condition is true, the action defined in this statement runs again and again until
the condition is broken. Therefore, we can rewrite the above statement as below. The
combination of condition and comparison operators inherently presents the logic
to terminate the loop.
The following example computes the sum of
numbers from 1 to 100. This is a popular example because of the genius, Gauss.
He solved this question when he was a child. But what I did was to eat candy
during my childhood. So, Gauss is really a genius because he knew that good
performance earns more candy.
沒有留言:
張貼留言