For Loops

This program first ask the user how many numbers, for loop to repeat the same instruction that many times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Read in numbers: find total, using a for loop
package numbers;
import java.util.*;
public class NumberTotal {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); //do just once
    int num, numbers, total=0;
    System.out.print("How many numbers are there to be added:");
    numbers=keyboard.nextInt();
    for(int i=0;i<numbers;i++) {
      System.out.print("Enter a number: ");
      num=keyboard.nextInt();
      total=total+num;
    }//loop
    System.out.print("Total="+total);
  }//main
}//class
CODE

Sample output:

How many numbers are there to be added:4
Enter a number: 8
Enter a number: 1
Enter a number: 3
Enter a number: 5
Total=17

NEXT: