### Introduction to array: why use arrays ?

• Motivational example

• Problem:

 Write a program that reads in and stores away 5 double numbers After reading in the numbers, the program computes the average of the numbers

• Solution: (Java program)

 ``` import java.util.Scanner; public class Avg1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); double a, b, c, d, e; // Hold 5 numbers double avg; System.out.print("Enter a number: "); a = in.nextDouble(); // Read in number System.out.print("Enter a number: "); b = in.nextDouble(); // Read in number System.out.print("Enter a number: "); c = in.nextDouble(); // Read in number System.out.print("Enter a number: "); d = in.nextDouble(); // Read in number System.out.print("Enter a number: "); e = in.nextDouble(); // Read in number avg = (a + b + c + d + e)/5; System.out.println(avg); // Print average } } ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link and save in a scratch directory To compile:   javac Avg1.java To run:          java Avg1

• Problem with this solution:

 It is not scalable The program becomes unmanageably large if the input size is large

• Solution:

• Organize the storage of the information in such a way that you can access the information through an index:

This kind of organized data is called an array data structure

• Java program using an array:

 ``` import java.util.Scanner; public class Avg2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); double[] a ; a = new double[5]; // Define an array of 5 elements double sum, avg; int i; // index for ( i = 0; i <= 4; i++ ) { System.out.print("Enter a number: "); a[i] = in.nextDouble(); // Read in number } /* --------------------------------------------------- Use the "running sum" algorithm to compute total --------------------------------------------------- */ sum = 0.0; for ( i = 0; i <= 4; i++ ) { sum = sum + a[i]; } avg = sum/5; System.out.println(avg); // Print average } } ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link and save in a scratch directory To compile:   javac Avg2.java To run:          java Avg2

• Note:

• The solution using an array is scalable

• If you want to process 1000000 numbers, just change the program to:

 ``` import java.util.Scanner; public class Avg2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); double[] a = new double[1000000]; double sum, avg; int i; // index for ( i = 0; i <= 999999; i++ ) { System.out.print("Enter a number: "); a[i] = in.nextDouble(); // Read in number } /* --------------------------------------------------- Use the "running sum" algorithm to compute total --------------------------------------------------- */ sum = 0.0; for ( i = 0; i <= 999999; i++ ) { sum = sum + a[i]; } avg = sum/1000000; System.out.println(avg); // Print average } } ```