Home Unit 6 Arrays
Post
Cancel

Unit 6 Arrays

Intro into Arrays

  • An array is a data structure used to implement a collection (list) of primitive or object reference data.

  • An element is a single value in the array

  • The **index** of an element is the position of the element in the array

    • In java, the first element of an array is at index 0. Start at INDEX 0 on AP EXAM.
  • The length of an array is the number of elements in the array.

    • length is a public final data member of an array

      • Since length is public, we can access it in any class!

      • Since length is final we cannot change an array’s length after it has been created

    • In Java, the last element of an array named list is at index list.length -1

A look into list Memory

int [] listOne = new int[5];

This will allocate a space in memory for 5 integers. Creating 5 spaces of memory to store memory in, specifically tell system to create these spaces.

  • Need to use the new keyword to specify arrays or else it will put random integer numbers in the array
1
2
ARRAY: [0, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

Using the keyword new uses the default values for the data type. The default values are as follows:

Data TypeDefault Value
byte(byte) 0
short(short) 0
int0
double0.0
booleanfalse
char‘\u0000’

What do we do if we want to insert a value into the array?

listOne[0] = 5;

Gives us the following array:

1
2
ARRAY: [0, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

What if we want to initialize our own values? We can use an initializer list!

int [] listTwo = {1, 2, 3, 4, 5};

Gives us the following array:

1
2
ARRAY: [1, 2, 3, 4, 5]
INDEX:  0  1  2  3  4

If we try to access an index outside of the range of existing indexes, we will get an error. But why? Remember the basis of all programming languages is memory. Because we are trying to access a location in memory that does not exist, java will throw an error (ArrayIndexOutOfBoundsException).

  • Because we are trying to reference some space that doesn’t exist since it’s not allocated

How do we print the array? Directly printing the array will not work, it just prints the value of the array in memory. We need to iterate through the array and print each value individually!

  • You have to reference a specific spot in the array, for example System.out.println(listOne[4]);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* lets take a look at the above */

int [] listOne = new int[5]; // Our list looks like [0, 0, 0, 0, 0]

listOne[2] = 33; // Our list looks like [0, 0, 33, 0, 0]
listOne[3] = listOne[2] * 3; // Our list looks like [0, 0, 33, 99, 0]

try {
    listOne[5] = 13; // This will return an error
} catch (Exception e) {
    System.out.println("Error at listOne[5] = 13");
    System.out.println("ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!");
}


System.out.println(listOne); // THIS DOES NOT PRINT THE LIST!! It prints the value in memory
System.out.println(listOne[4]); // This will actually print the vaules in the array
1
2
3
4
Error at listOne[5] = 13
ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!
[I@6df87a1c
0

Popcorn Hacks!

Write code to print out every element of listOne the following

1
2
3
for (int i = 0; i < listOne.length; i++){ 
    System.out.println(listOne[i]);
}
1
2
3
4
5
0
0
33
99
0
1
2
3
for (int i: listOne) {
    System.out.println(i);
}
1
2
3
4
5
0
0
33
99
0

Reference elements

Lists can be made up of elements other than the default data types! We can make lists of objects, or even lists of lists! Lets say I have a class Student and I want to make a list of all students in the class. I can do this by creating a list of Student objects.

1
2
Student [] classList;
classList = new Student [3];

Keep in mind, however, that the list won’t be generated with any students in it. They are initialized to null by default, and We need to create the students and then add them to the list ourselves.

1
2
3
classList[0] = new Student("Bob", 12, 3.5);
classList[1] = new Student("John", 11, 4.0);
classList[2] = new Student("Steve", 10, 3.75);

Popcorn hacks!

Use a class that you have already created and create a list of objects of that class. Then, iterate through the list and print out each object using: 1) a for loop 2) a while loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class Cat {
    public String Name; 
    public int Age;
    public String Color;

    public Cat(String name, int age, String color) { 
        Name = name;
        Age = age;
        Color = color;
    }

    public String getName() { 
        return Name;
    }

    public int getAge() { 
        return Age;
    }

    public String getColor() {
        return Color;
    }

    public static void main(String[] args) { 
        Cat [] catList;
        catList = new Cat [3];
        
        catList[0] = new Cat("Apollo", 3, "Orange");
        catList[1] = new Cat("Porsha", 10, "Brown");
        catList[2] = new Cat("Biggie", 9, "Grey");
        
        // for loop
        System.out.println("For Loop");
        for (int i = 0; i < catList.length; i++) {
            System.out.println(catList[i].getName() + ": " + catList[i].getAge() + " yrs, " + catList[i].getColor() + " color");
        }

        // while loop
        System.out.println("\nWhile Loop");
        int j = 0;
        while (j < catList.length){
            System.out.println(catList[j].getName() + ": " + catList[j].getAge() + " yrs, " + catList[j].getColor() + " color");
            j++;
        }
    }
}
Cat.main(null)
1
2
3
4
5
6
7
8
9
For Loop
Apollo: 3 yrs, Orange color
Porsha: 10 yrs, Brown color
Biggie: 9 yrs, Grey color

While Loop
Apollo: 3 yrs, Orange color
Porsha: 10 yrs, Brown color
Biggie: 9 yrs, Grey color

Enhanced for loops

The enhanced for loop is also called a for-each loop. Unlike a “traditional” indexed for loop with three parts separated by semicolons, there are only two parts to the enhanced for loop header and they are separated by a colon.

The first half of an enhanced for loop signature is the type of name for the variable that is a copy of the value stored in the structure. Next a colon separates the variable section from the data structure being traversed with the loop.

Inside the body of the loop you are able to access the value stored in the variable. A key point to remember is that you are unable to assign into the variable defined in the header (the signature)

You also do not have access to the indices of the array or subscript notation when using the enhanced for loop.

These loops have a structure similar to the one shown below:

1
2
3
4
5
6
for (type declaration : structure )
{
    // statement one;
    // statement two;
    // ...
}

Popcorn Hacks!

Create an array, then use a enhanced for loop to print out each element of the array.

1
2
3
4
int[] arr = {4, 3, 93, 94, 6};
for (int i: arr) {
    System.out.println(i);
}
1
2
3
4
5
4
3
93
94
6

Min maxing

It is a common task to determine what the largest or smallest value stored is inside an array. in order to do this, we need a method that can ake a parameter of an array of primitive values (int or double) and return the item that is at the appropriate extreme.

Inside the method of a local variable is needed to store the current max of min value that will be compared against all the values in the array. you can assign the current value to be either the opposite extreme or the first item you would be looking at.

You can use either a standard for loop or an enhanced for loop to determine the max or min. Assign the temporary variable a starting value based on what extreme you are searching for.

Inside the for loop, compare the current value against the local variable, if the current value is better, assign it to the temporary variable. When the loop is over, the local variable will contain the approximate value and is still available and within scope and can be returned from the method.

Popcorn Hacks!

Create two lists: one of ints and one of doubles. Use both a standard for loop and an enhanced for loop to find the max and min of each list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int[] intList = {9, 3, -8, 38, 21};
int max = intList[0];
for (int i = 1; i < intList.length; i++) {
    if (intList[i] > max){
        max = intList[i];
    }
}
System.out.println("Maximum: " + max);

int min = intList[0];
for (int j : intList) {
    if (j < min){
        min = j;
    }
}
System.out.println("Minimum: " + min);
1
2
Maximum: 38
Minimum: -8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double[] dubList = {5.9, 2.0, 4.5, 9.1, 9.9, 8.4};
double max=dubList[0];
for (int i = 1; i < dubList.length; i++) { // note: int i because i is used for index of list, so it's int not double
    if (dubList[i] > max){
        max = dubList[i];
    }
}
System.out.println("Maximum: " + max);

double min = dubList[0];
for (double j: dubList){
    if (j < min){
        min = j;
    }
}
System.out.println("Minimum: " + min);
1
2
Maximum: 9.9
Minimum: 2.0

Hacks

Given an input of N integers, find A, the maximum, B, the minimum, and C the median.

Print the following in this order:

  • A + B + C
  • A - B - C
  • (A + B) * C

Sample data:

INPUT:
5
1 2 3 4 5

OUTPUT:
9 1 18

INPUT:
9
2 4 6 8 10 10 12 14 16

OUTPUT:
28 6 180

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.Scanner;

public class MaxMinMed {
    public int findMax(int[] arr, int n) {
        int max = arr[0];
        for (int i = 1; i < n; i++) {
            if (arr[i] > max){
                max = arr[i];
            }
        }
        return max;
    }
    
    public int findMin(int[] arr, int n) {
        int min = arr[0];
        for (int i = 1; i < n; i++) {
            if (arr[i] < min){
                min = arr[i];
            }
        }
        return min;
    }

    public double findMed(int[] arr, int n) {
        // sort order
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        
        if ((n % 2) != 0) {
            // odd amt in list
            return arr[n/2];
        } else {
            // even amt in list
            int mid1 = arr[n/2 - 1];
            int mid2 = arr[n/2];
            return (double) (mid1 + mid2) / 2.0;
        }
    }
}

public void main(String[] args) {
    // Scanner object for user input
    Scanner scanner = new Scanner(System.in);

    // user enter amt of integer
    System.out.println("Enter an integer (n) for amount of integers: ");
    int n = scanner.nextInt();
    System.out.println(n+"\n");
        
    // allocate memory
    int [] arr = new int[n];

    // user enter integers
    System.out.println("Enter your integers: ");
    for (int i = 0; i<n; i++){
        int curr_entered = scanner.nextInt();
        arr[i] = curr_entered;
        System.out.println(curr_entered);
    }

    MaxMinMed obj = new MaxMinMed();
    int A = obj.findMax(arr, n);
    int B = obj.findMin(arr, n);
    double C = obj.findMed(arr, n);

    System.out.println("\nMaximum: " + A + ", Minimum: " + B + ", Median: " +C);
    System.out.println("\n"+ A + B + C);
    System.out.println(A - B - C);
    System.out.println((A + B) * C);
}

main(null)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Enter an integer (n) for amount of integers: 
8

Enter your integers: 
4
23
10
2
34
41
89
90

Maximum: 90, Minimum: 2, Median: 28.5

90228.5
59.5
2622.0

For extra, create your own fun program using an array

  • Find mean of user input (n) random integers 1-100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.Scanner;
import java.util.Random;

public class mean {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        // user enter amt of integer
        System.out.println("Enter an integer (n) for amount of integers: ");
        int n = scanner.nextInt();
        System.out.println(n+"\n");

        int[] randNums = new int[n];

        // genreate random nums
        for (int i = 0; i < n; i++) {
            randNums[i] = random.nextInt(101); // random nums from 1-100
        }
        System.out.println("Random numbers: ");
        for (int num : randNums) {
            System.out.print(num + ", ");
        }

        // find mean
        double sum = 0;
        for (int num: randNums){
            sum += num;
        }
        double mean = sum/n;

        System.out.println("\n\nMean: "+ mean);
    }
}
mean.main(null)
1
2
3
4
5
6
7
Enter an integer (n) for amount of integers: 
9

Random numbers: 
24, 78, 88, 58, 22, 43, 94, 15, 14, 

Mean: 48.44444444444444
This post is licensed under CC BY 4.0 by the author.