For Loops

Consider the program below. This program reads in a number and adds to the total 3 times. There is just one variable for the input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Read in 3 numbers: find total, version 2
package numbers;
import java.util.*;
public class Numbers {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); //do just once
    int num, total=0;
    System.out.print("Enter a number: ");
    num=keyboard.nextInt();
    total=total+num;
    System.out.print("Enter a number: ");
    num=keyboard.nextInt();
    total+=num; //same as total=total+num;
    System.out.print("Enter a number: ");
    num=keyboard.nextInt();
    total+=num; //same as total=total+num;
    System.out.print("Total="+total);
  }//main
}//class
CODE
Enter a number:34
Enter a number:10
Enter a number:-5
Total=39

If we can rewrite a program to repeat the same lines several times, we can use a loop instead.

NEXT: