Arrays

A data structure

Chapter 7

Data structures

    A data structure is a way to store related data items of the same type.

    We need to talk about how arrays are

    Declared

    Created

    Initialized

    Then talk about how to put data into arrays, and access data stored in an array

    Then we will talk about ways arrays are often used, and some examples.

 


Arrays

    An array is a group of variables containing values that all have the same type.

    The array as a whole has a name, then the individual elements are referenced using subscripts.

    We could declare an array of ints called numbers int[ ] numbers = new int[5];

    This sets aside in RAM space for 5 ints

    The general for is
type[ ] array_name = new type[size]

    The space is contiguous; i.e. it is all together


Automatic initialization of arrays

    When an array is first created, all the values are automatically initialized

    To zero for numbers int[ ] or double[ ]

    To false for a boolean[ ] array

    To null for an array of objects

    Each element in the array is specified by an integer index that is placed inside square brackets

    For example, the expression numbers[4] denotes the element of the array with index 4


Storing and accessing data

    You can store a value at a specific location with an assignment statement such as
numbers[4] = 567;

    To access the data value at index 4, you use the expression numbers[4] as you would any other int.

    Example:
System.out.println(“The value is “ + numbers[4]);

 

Examples

    Assume we declare an array of ints
int[ ] numbers = new int[10]

    Each element in the array is specified by an integer index that is placed inside square brackets

    You can store a value at a specific location using the index
numbers[3] = 897;

    You can also access the data at a specific index
int OneNum = numbers[2]; or
System.out.println(numbers[2]);

 

Indexing an array

    The indices of a Java array always start at zero

    They go to one minus the size of the array

    Example:
double[ ] data = new double[8]

    The indices go from 0 to 7

    If you say data[8] = 56.65 you will get an index out of bounds error; the highest index is 7

    The array itself keeps track of its length
data.length will return 8

    The general form to find the length of an array is arrayName.length


Where to put the [ ]

    Some authors put the square brackets after the type

    Others put them after the array name.

    String name[ ] = new String[10];
is equivalent to
String[ ] name = new String[10];

 

Initializing an array with data

    You can put values in an array at the time your declare and create it

    int[ ] num = new int[10,20,30,40,50];

    This will create an array with 5 slots and put the numbers in the slots.


A loop is used to manipulate an array

    Assume we initialize an array, then want to print out the values.

int[ ] num = new int[10, 20, 30, 40, 50];

for(int i = 0; i < num.length; i++)

System.out.println(“ The number is “ + num[i]);

    Note the terminating condition; the length of the array is used.

    We could use a loop to get data into the array; assume a Scanner object in has been declared

int num = new int[5];

for(int i = 0; i < num.length; i++)

      {    System.out.println(“Please enter an integer”);

num[i] = in.nextInt( );
}

 

Using magic numbers

    Generally, in a program, it is considered poor practice to use hard numbers.

    It is much better to use a variable or constant to declare a constant then use it

    This makes it easier to change the size of the array later.

    To declare a constant:
final int MAX = 10;

The use the constant in place of the number
int [ ] num = new int[MAX];

The general form:
final type CONSTANT_NAME = value;

 

Working with arrays

    Write a program that asks the user to enter ten integers, save them to be used later, outputs the smallest one

    Let’s do it in pseudocode first

    Import Scanner class

    Declare Scanner object

    Declare a constant for array size

    Declare the array

    Declare an in small initialized to a large number

    In a for loop

          ·ask the user for a number

          Store it in the array

          If it is smaller than small, set it to small

            Output small


Writing a program using arrays

We want a program that will average a set of numbers.

public class SumArray

{

 

public static void main( String args[ ] )

{
int array[ ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int total = 0;

// add each element's value to total
for ( int counter = 0; counter < array.length; counter++ )
total += array[ counter ];

int avg = total/array.length

System.out.printf(
Average of array elements: %d\n", avg );
}
// end main|
} // end class SumArray


Using the elements of an array as a counter

public class RollDie

{

 

public static void main( String args[ ] )
{
Random randomNumbers = new Random();
int frequency[ ] = new int[ 7 ];
// array of frequency counters


// roll die 6000 times; use die value as frequency index
for ( int roll = 1; roll <= 6000; roll++ )
++frequency[ 1 + randomNumbers.nextInt( 6 ) ];

System.out.printf( "%s%10s\n", "Face", "Frequency" );

 

// output each array element's value
for ( int face = 1; face < frequency.length; face++ )
System.out.printf( "%4d%10d\n", face, frequency[ face ] );

} // end main
// end class RollDie


Arrays of objects

    Arrays are often used to hold objects as well as primitives

    Suppose we have a class Person that has as instance variables name and phone, both Strings.

    Then on object of type Person is the name and phone number of one person.

    We can make an array of type Person to hold the names and phone numbers of people we often call.


public class Person

{    private String name, phone;


     public Person()

     {    name = null;

           phone = null;

     }


     public Person(String perName, String perPhone)

     {    name = perName;

           phone = perPhone;

     }


     public String toString( )

     {    return name + " " + phone; }


}

import java.util.Scanner;

public class PhoneBook

{

public static void main(String[] args)

     {    final int MAX = 2;

Person[] entry = new Person[MAX];

String newName, newNum;

Person oneEntry;

Scanner in = new Scanner(System.in);

 

for(int i=0; i<entry.length; I++)

           {      System.out.print("Enter the person's name ");

newName = in.nextLine();

System.out.print("Enter the person's phone number ");

newNum = in.nextLine();

oneEntry = new Person(newName, newNum);

entry[i] = oneEntry;

} // end for

 

for(int i=0; i<entry.length; i++) // output the entries in the phone book

System.out.println(entry[i]);

     } // end main