For Loops

Consider the program below. This program reads in 3 numbers and finds the total:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package numbers;
import java.util.*;
public class Numbers {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); //do just once
    int num1, num2, num3, total;
    System.out.print("Enter a number: ");
    num1=keyboard.nextInt();
    System.out.print("Enter a number: ");
    num2=keyboard.nextInt();
    System.out.print("Enter a number: ");
    num3=keyboard.nextInt();
    total=num1+num2+num3;
    System.out.print("Total="+total);
  }//main
}//class
CODE
Enter a number:6
Enter a number:90
Enter a number:5
Total=101

The program works, and gives the right total. If we want to read in and find the total of 2 or 3 numbers, using a loop may not make much difference. But what if we want to read in and find the total of 10 numbers or 100?

The first step, is to look at the program above and rewrite it so that it uses just 2 variables.

NEXT: