Skip to the content.

Unit 6 - Arrays

Unit 6 Team Teach - Arrays

By: (J)onathan, (I)an, (T)arun, (S)rijan

6.1 Array Creation and Access

MUST KNOW TERMS

  • Array: A data structure that holds a group of object references.
  • Element: A single item stored inside an array.
  • Element index: The location of an element in the array (in Java AND PYTHON(called a list) the first element is at index 0).
  • Array length: Number of elements in the Array

Declaring Array

To declare an array, you need the name of the array and the datatype.

Syntax: dataType[] arrayName;

(note in python that no need to declare which is called dynamic typing)

int[] grades; // Declare an integer array
String[] class_list; // Declare a string array
boolean[] light_switch;

Creating an Array

Gives memory for the array but we need to specify its size for java compared to python(with arraylists in the next lesson you won’t)


// Syntax: arrayName = new dataType[size];
int[]grades = new int[5]; // Create an integer array with 5 elements
String[]class_list = new String[3]; // Create a string array with 3 elements
boolean[]light_switch= new boolean[5];

// Can also predefine the terms rather than setting to default value
int[]grades={100,90,100,10,20};
boolean[]light_switch={true,false,true,false,true};


numbers=list()
names=list()
light_switch=list()

Printing out an Array

import java.util.Arrays;
// Printing out the array with java method
int[]grades={100,90,100,10,20};
System.out.println(Arrays.toString(grades));
[100, 90, 100, 10, 20]

Popcorn Hack 1(Time 0.5 minute)

Create an array that represents numerous car brands(Audi, toyota,etc. )

import java.util.Arrays;
String[]cars={"Audi", "Toyota"};
System.out.println(Arrays.toString(cars));
[Audi, Toyota]

Array with custom Objects

class Coder{
    public boolean codecodecoder;
    public int age;
    Coder(boolean codecodecoder, int age){
        this.codecodecoder=codecodecoder;
        this.age=age;
    }
    
}
Coder[]allthecoders=new Coder[5];


for(int i=0;i<allthecoders.length;i++){
    allthecoders[i]=new Coder(true,10);
}

System.out.println(Arrays.toString(allthecoders));
[REPL.$JShell$26$Coder@5a4be8a2, REPL.$JShell$26$Coder@548c1d9b, REPL.$JShell$26$Coder@50b383d2, REPL.$JShell$26$Coder@15b117a0, REPL.$JShell$26$Coder@10baf34c]

Accessing Array Elements

Acsessing an element’s value using it’s index in the array

int[] grades = {10, 20, 30, 40, 50};
int element = grades[1]; // Access the second grade (20) using index 2
System.out.println(element); // Output: 30
20
# Python translation/example
grades=[10,20,30,40,50]
student1_grade=grades[0] # the first element in the array/list
print(student1_grade)

10

Popcorn Hack #2(Time 1.5 Minutes)

  1. Make an array of chars, representing people’s grades
  2. Try to adjust the letter grade of at least 3 people
String[] grades = {"A", "B", "C"};
grades[1]="A";
grades[2]="A";
grades[0]="A";
// Access the second grade (20) using index 2
System.out.println(Arrays.toString(grades)); // Output: 30
[A, A, A]

Array Length

Finding the length of the array.

int[] Students_commits = {10, 20, 30, 40, 50, 60, 70, 80, 90}; //number of commits for each student
int length = Students_commits.length; // Get the length of the array and assign to an integer variable
System.out.println("Array length and number of coders: " + length); // Output: Array length: 5
Array length and number of coders: 9
grades=[10,20,30,40,50,60,70,80,90]
length=len(grades)
print("number of students",length)
number of students 9

Modifying Array Elements

Updates the value of a specific element in the array.

// integer array

int[] grades = {10, 20, 30, 40, 50};
System.out.println("Before: "+Arrays.toString(grades));
grades[2] = 35; // Change the third grade to 35
System.out.println("After: "+Arrays.toString(grades));


// boolean array

boolean[]light_switch={true,false,true,false}; //array of light switches with true meaning the light is on and false meaning its off
System.out.println("Before: "+Arrays.toString(light_switch));
light_switch[0]=false; // turn off the first switch    true-->false
System.out.println("After: "+Arrays.toString(light_switch));

// String array
String[]student_names={"Bob", "Sir Mort"," Sir Tarun", "Sensei Wu"};
System.out.println("Before: "+Arrays.toString(student_names));
student_names[0]="Sir Jonathon";
System.out.println("After: "+Arrays.toString(student_names));


Before: [10, 20, 30, 40, 50]
After: [10, 20, 35, 40, 50]
Before: [true, false, true, false]
After: [false, false, true, false]
Before: [Bob, Sir Mort,  Sir Tarun, Sensei Wu]
After: [Sir Jonathon, Sir Mort,  Sir Tarun, Sensei Wu]

# Python translation/example
grades=[10,20,30,40]
print("Before",grades)

grades[1]=100 # changing the secon d element to 100
print("After",grades)
Before [10, 20, 30, 40]
After [10, 100, 30, 40]

Iterating Through an Array

Loops through the array, printing each element.

int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) { // going from the first index(0) to the last index(length of array-1)
    System.out.println("Index "+i+": "+numbers[i]);
}
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50
numbers=[10,20,30,40]
for i in range(0,len(numbers)):
    print("Index",i,":",numbers[i])
Index 0 : 10
Index 1 : 20
Index 2 : 30
Index 3 : 40

Topic 6.2 - Traversing Array (1D)

Using iteration statements (standard for loops and while loops) to access each element in an array.

The Classic For Loop

  • An array in java is indexed from n1 to the number of elements n2.

Review on what a for loop is?

  • init: The init expression is used to initialize a variable (executed once)
  • condition: The loop executes the condition statement every iteration.
  • incr/decr: The increment/decrement statement applied to the variables which updates the initial expression. forLoopExample

Here’s some basic code (boring stuff):

import java.util.Random;

public class RandomArray {
    public static void main(String[] args){
    int [] list = new int[6];
    Random rand = new Random(); 

    // FOR LOOP 1
    for (int i = 0; i < list.length; i++){
        list[i] = rand.nextInt(4);
    }

    // FOR LOOP 2
   for(int element: list){
        System.out.println(element);
    }

   }

   }

  RandomArray.main(null);
0
0
1
2
2
2

forLoopGif

For Loop: Accessing List Elements

Popcorn hack question

Which part of the following code would I want to change if I wanted to access all odd indices of the list.

// EVEN
int[] list = {0, 1, 2, 3, 4, 5};
System.out.println("Even Index");
for(int index = 1; index < list.length; index+=2){
    System.out.println(list[index]);
}
Even Index


1
3
5

Standard While Loop

Does the following loop accomplish traversing the array?

int [] list = new int[5];
int index = 0; 

while (index < list.length) 
{
    // Do something
    index ++; 
}

System.out.println("New index: " + index);
New index: 5

Popcorn hack question:

This while loop and the for loop we used earlier accomplish the same task. The main difference is that after the loop is completed, the variable ‘index’ in the while loop will still exist. The variable ‘i’ in the for loop will not. Why?

The “i” is a variable local to the for loop and therefore cannot be accessed at a global scale.

Bounds Errors

When traversing an array, we need to be careful with the indices to avoid an ArrayIndexOutOfBoundsException being thrown.

**ATTENTION: MOST COMMON MISTAKE: **

  1. What is wrong with the for loop and while loop below? Why does this produce an ArrayIndexOutOfBoundsException error? The first index is 0 making the equation invalid. You must change the signs or add a -1

Off by One Error : missing the first or last element of an array when trying to traverse

Developing Methods Using Arrays

Reviewing common methods asked on AP Exams FRQs

Average Value

Popcorn Hack:

Create/complete the code in order to return the average grade of all grades in the list of grades.

Homework:

Have the code print “Man, you guys need to study more” if the grades are beneath a certain percentage.

Bonus: Have the code iterate through the list and add some points to each grade because you’re a very generous grader.

public class GradeAverage {
    public static void main(String[] args) {
        /* grades out of 100 */
        int[] grades = {90, 50, 70, 20, 80, 97};
        int sum = 0;
        double average;
        
        for (int i = 0; i<grades.length;i++) {
            sum += grades[i]; 
        }
       
        average = (double) sum / grades.length; /* missing code */ 

        
        System.out.println("The average of the grades is: " + average);
        
        if (average<85){
            System.out.println("Man you need to study.");
            for (int i = 0; i<grades.length;i++) {
                grades[i] = grades[i] + 2;
                sum += grades[i]; 
            }
            System.out.println("The new grades list is:");
            System.out.println(Arrays.toString(grades));
        }
    }
}

GradeAverage.main(null);
The average of the grades is: 67.83333333333333
Man you need to study.
The new grades list is:
[92, 52, 72, 22, 82, 99]

6.3 Enhanced For Loop for Arrays

The “Enhanced For Loop” is otherwise known as a for each loop. This provides a simple way to loop through iterable data structures such as arrays and lists. The syntax for this loop is as follows,

for(dataType element : array) { 
    //code to be ran on an element
}

If this syntax is unfamiliar, perhaps the Python version can be used as reference

for element in array:
    #code to be ran on element

Here’s an example of using these types of loops to calculate the sum of an Array Do note the iterated element has to be of the data type in the array.

int sum = 0;
int[] numArray = {1,2,3,4,5,6,7,8,9,10};
for(int numElement : numArray)
{
    System.out.println(numElement);
    sum += numElement;
}
System.out.println(sum);
1
2
3
4
5
6
7
8
9
10
55

Popcorn Hack: Rewrite For Loop with For Each Loop

You are working as an intern for a car sales company at their IT department. Your new task your boss gave you is to post the prices and names of the newest cars to be sold The previous IT developer couldnt get their for loop to work. Could you fix the issue?

Given the following code, rewrite the script to use a for each loop instead of the for loop and fix the problem

import java.util.HashMap;
import java.util.Map;
        Map<String, Integer> carMap = new HashMap<String, Integer>();

        carMap.put("MortMobile ",9999);
        carMap.put("CSAwesomeCar ",500);
        carMap.put("ArrayceCar ",5000);
        
        for(Map.Entry<String, Integer> car : carMap.entrySet())
        {
            System.out.println(car.getKey() + car.getValue());
        }
ArrayceCar 5000
MortMobile 9999
CSAwesomeCar 500

Limitations On Enhanced For Loops

It does not allow for access to the index number of the element, You cannot modify elements of the loop You cannot get a specific index in the same way array[ i ] can

Final Hack

Finish the following code with a for each and normal for loop

int[] nums = {1,2,3,4,5,6,2000};
for(int num : nums)
{
    System.out.println(num % 2==0);
}

for(int i=0;i<nums.length;i++)
{
    System.out.println(nums[i] % 2 ==0);
}
false
true
false
true
false
true
true
false
true
false
true
false
true
true

6.4 Developing Algorithms Using Arrays

Finding Maximum and Minimum of Arrays

We’ve done this in python many times in the past, but in java it will be different. Steps:

  1. Initialize a variable to store a maximum value
  2. Iterate through every element in the list
    • In python we would use for x in list but this isn’t possible now, instead we must use an enhanced for loop
  3. Check if element is greater than max, if so replace
  4. return element
/* function, takes in array of doubles as values */
private double findMax(double [] values) {
    /* Sets max to first number in the list. Min Value could be the min value */
    double max = values[0];

    /* enhanced for loop notation */
    for (double value : values) {
        /* check for max */
        if (value > max) {
            max = value;
        }
    }
    return max;
}

/* run on array */
double[] nums = {1,2,3,4,5,6,2000, 123.123, 1230912839018230.123901823};
System.out.println(findMax(nums));
1.23091283901823E15

Popcorn Hack

Implement a function to find the minimum of the EVEN INDEXED elements in array of integers.

private double findMinEven(int [] values) {
    double min = values[0];
    for(int i=0;i<values.length;i+=2) {
        if (values[i] < min) {
            min = values[i];
        }
    }
    return min;
}

int[] nums = {5, 2, 3, 4, 5};
System.out.println(findMinEven(nums));
3.0

Ok wait but i don’t want to copy this every time. what happened to python’s .max?

double[] nums = {1,2,3,4,5,6,2000};
System.out.println(Arrays.stream(nums).max().getAsDouble())

Shifting Arrays

Oftentimes we need to shift an array. ex. Shifting an array right two: Original: {“a”, “b”, “c”, “d”} Final: {“d”, “c”, “a”, “b”}

How do we do this?

  1. Create a new array
  2. Iterate through each element in the array
  3. Place in appropriate spoce
int [] numbers = {1,2,3,4,5,6,7,8,9,10};

int shift = 8;

/* function */
private int [] shiftRight(int [] values, int shift) {
    /* declare new array */
    int [] shifted = new int [values.length];
    /* iterate through each array */
    for (int index = 0; index < values.length; index++) {
        /*
         Breakdown:
         shifted [new index] = numbers[index] (old value)

         WAIT! but i'm adding a value to somewhere in the middle of the array! 
         we couldn't do that in python but since we specified the type and length of the array, this is possible in java

         Calculating the new index:
         1. we add the shift to the index
         2. handle overflow: we use % to take the modulo operation
         */
        shifted [Math.abs((index + shift) % numbers.length)] = numbers[index];
    }
    return shifted;
}

for ( int value : shiftRight(numbers, shift)) {
    System.out.println(value);
}
3
4
5
6
7
8
9
10
1
2

Challenge Hack: Create a function that iterates through every X items and shifts only those elements Y shift left.

Example: ({1, 2, 3, 4, 5, 6}, Y = 1, X = 2) Output: {5, 2, 1, 4, 3, 6}

Example: ({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, Y = 2, X = 3) Output: {10, 2, 3, 1, 5, 6, 4, 8, 9, 7}

int [] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};

int shift = 2;
int space = 2;

private int [] shiftRight(int [] values, int shift, int space) {
    
    int [] shifted = new int [values.length];
    for (int i = 0; i < values.length; i++) {
        shifted[i] = values[i];
    }

    for (int index = 0; index < values.length; index+=space) {
        shifted [Math.abs((index + shift) % numbers.length)] = numbers[index];
    }
    return shifted;
    
}

for ( int value : shiftRight(numbers, shift, space)) {
    System.out.println(value);
}
19
2
1
4
3
6
5
8
7
10
9
12
11
14
13
16
15
18
17
20