More Examples

In this lesson, we will continue our discussion of the for statement by presenting a few more examples of its use.

A counted loop to add numbers that are read

In the previous chapter, we used a while loop to compute the sum of numbers that a user enters at the keyboard. We can use a for loop to accomplish the same task:

// Purpose: Computes the sum of numbers read from the user.
// Given: howMany is the number of numbers to be read.
double sum = 0; // Sum of the numbers read
for (int counter = 1; counter <= howMany; counter++)
{
   System.out.println("Please enter the next number: ");
   double number = keyboard.nextDouble();
   sum = sum + number;
} // End for
// sum contains the sum of the numbers read

Get hands-on with 1400+ tech skills courses.