More Examples
Explore how to use for loops effectively in Java, including nested loops for pattern creation and loop control using characters and real numbers. Understand common pitfalls like empty loop bodies. This lesson helps you write clearer, more concise repetitive code to solve practical programming tasks.
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
Note that the for statement, like the while statement, can have a compound
statement for its body. After the loop, sum contains the sum of the numbers read.
If we wanted to ...