Working with a large amount of data

  • Suppose we want to read in 4 numbers and compute the average:

          public static void main(String[] args) 
          {
              Scanner input = new Scanner(System.in);
              
              double number1 = input.nextDouble();
              double number2 = input.nextDouble();
              double number3 = input.nextDouble();
              double number4 = input.nextDouble();
              
              double avg;
              avg = (number1 + number2 + number3 + number4)/4;
              System.out.println(avg);
          } 

  • Problem with a large amount of data:

    • We need to define many variables

    Managing many individual variables is not practical

DEMO: demo/08-array/01-intro/IndividualVars.java

Working with a large amount of data

  • The array data structure:

    • An array can store a number of values of the same data type.

    • Individual array elements can be accessed using an index

    Example:

       public static void main(String[] args) 
       {
           Scanner input = new Scanner(System.in);
      
           double[] num = new double[4];    // Defines an array
      
           for ( int i = 0; i < 4; i++ )
      	 num[i] = input.nextDouble(); // num[i] is ith elem in array
      
           double sum = 0;
           for ( int i = 0; i < 4; i++ )
      	 sum = sum + num[i];
           System.out.println(sum/4);
       } 

DEMO: demo/08-array/01-intro/Array.java

Arrays

  • Array:

    • An array is used to store a collection of data of the same data type

  • Note:

      • In some programming languages (e.g.: Python), an array can store data of different data types

  • Strengths of arrays:

      • Instead of defining individual variables, such as number0, number1, . . . , and number99,

      • We can define one array variable such as numbers

      • After defining the array variable, we can use numbers[0], numbers[1], . . . , and numbers[99] as individual variables !!

Strength of arrays illustated

  • Using arrays, we can easily accommodate a large amount of data, e.g.: 1,000,000 values:

          public static void main(String[] args) 
          {
              Scanner input = new Scanner(System.in);
              
              double[] num = new double[1000000];
      
      	for ( int i = 0; i < 1000000; i++)
      	    num[i] = input.nextDouble();
      
              double sum = 0;
      	for ( int i = 0; i < 1000000; i++)
      	    sum = sum + num[i];
              System.out.println(sum/1000000);
          } 

In this chapter we will learn how to work with arrays