More Examples
Explore the use of loops in Java to compute sums from user inputs. Understand counted loops for fixed iterations and sentinel-controlled loops for flexible input lengths. Learn how to implement sentinel values to signal the end of input and handle different user data scenarios effectively.
We'll cover the following...
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 ...