More Examples

In this lesson, we will look at more examples of the while statement.

Computing the sum of numbers that are read

Suppose that we wanted to compute the average of a group of numbers that a user enters at the keyboard. We first would have to compute their sum.

The logic of a loop to perform this first task might appear as follows:

sum = 0
while (there are more numbers to read)
{
   number = next number read from the keyboard
   sum = sum + number
}

How do we know how many numbers to read? The simplest way for the programmer to get the answer to this question is to ask the user, so that is what we will do next.

A counted loop

After reading the expected size of the input data set, we will use a counter to control the loop. The following code implements this idea:

Get hands-on with 1200+ tech skills courses.