L04 - Iteration Lab - Part 2 - The Three Loops
Enter the following program and fill in the missing pieces so that the three different styles of loops compute the sum of numbers.
public class Loops {
public static void main(String[] args) {
//sum the numbers from 1 to 5 using a for loop
int sum = __________;
for(_________;_________;_________) {
sum = sum + i;
}
System.out.println("The sum of the numbers from 1 to 5 is " + sum);
//sum the numbers from 1 to 10 using a while loop
sum = 0;
int i = 0;
while (__________) {
i = __________;
sum = sum + i;
}
System.out.println("The sum of the numbers from 1 to 10 is " + sum);
//sum the numbers from 1 to 15 using a do...while loop
sum = 0;
i = 0;
do {
i = __________;
sum = sum + i;
} while (__________);
System.out.println("The sum of the numbers from 1 to 15 is " + sum);
}
}
You can check your results by using the formula 1 + 2 + ... + n = n(n+1)/2
Sample Output
The sum of the numbers from 1 to 5 is 15
The sum of the numbers from 1 to 10 is 55
The sum of the numbers from 1 to 15 is 120
No Comments