Arrays

When variables have the same purpose in a program, it is often more efficient to use an array.

The program below reads in three numbers, then prints them.

The statement double[] num= new double[3]; allocates space in memory for three decimal numbers. The three numbers are referred to as num[0], num[1], and num[2]. In speaking we often say "num sub 1." where "sub" is short for "subscript".

array

The number inside brackets is the subscript or index. The subscripts always start with 0.

Once a variable is declared as an array, the subscript must be included to refer to the elements.

One of the advantages of an array is that the subscript can be a variable. A for loop can be used to read in an array of numbers or print them out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Arrays: Read 3 numbers
package numbers;
import java.util.*;
public class Numbers {
  public static void main(String[] args) {
	  Scanner keyboard=new Scanner(System.in); 
	  double num[3];
	  for(int i=0;i<3;i++){
		  System.out.print("Enter a number:"); 
		  num[i]=keyboard.nextDouble();
	  }//for loop to input
	  for(int i=0;i<3;i++){
		  System.out.println(num[i]); 
	  }//for loop to output
  }//main
}//class
CODE

NEXT: