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.
-
The length of an array is the number of elements in the array.
-
length
is apublic final
data member of an array-
Since
length
ispublic
, we can access it in any class! -
Since
length
isfinal
we cannot change an array’slength
after it has been created
-
-
In Java, the last element of an array named
list
is at indexlist.length -1
-
A look into list Memory
int [] listOne = new int[5];
This will allocate a space in memory for 5 integers.
ARRAY: [0, 0, 0, 0, 0] INDEX: 0 1 2 3 4
sql Copy code
Using the keyword new uses the default values for the data type. The default values are as follows:
Data Type | Default Value |
---|---|
byte | (byte) 0 |
short | (short) 0 |
int | 0 |
double | 0.0 |
boolean | false |
char | ‘\u0000’ |
What do we do if we want to insert a value into the array?
listOne[0] = 5;
Gives us the following array:
ARRAY: [0, 0, 0, 0, 0] INDEX: 0 1 2 3 4
perl Copy code
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:
ARRAY: [1, 2, 3, 4, 5] INDEX: 0 1 2 3 4
csharp Copy code
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
).
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!
```java /* 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 values in the array Popcorn Hacks! Write code to print out every element of listOne using a for loop:
java Copy code /* popcorn hacks go here */ for (int i = 0; i < listOne.length; i++) { System.out.println(listOne[i]); } 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! Let’s 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.
java Copy code 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.
java Copy code 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 a for loop and a while loop:
java Copy code /* Popcorn hacks go here */ class Student { String name; int age; String grade;
public Student(String name, int age, String grade) {
this.name = name;
this.age = age;
this.grade = grade;
} }
public class Main { public static void main(String[] args) { // Create a list of Student objects Student[] students = { new Student(“Alice”, 18, “A”), new Student(“Bob”, 19, “B”), new Student(“Charlie”, 20, “C”) };
// Using a for loop to iterate through the list and print each object
System.out.println("Using a for loop:");
for (Student student : students) {
System.out.println("Name: " + student.name + ", Age: " + student.age + ", Grade: " + student.grade);
}
// Using a while loop to iterate through the list and print each object
System.out.println("\nUsing a while loop:");
int index = 0;
while (index < students.length) {
Student student = students[index];
System.out.println("Name: " + student.name + ", Age: " + student.age + ", Grade: " + student.grade);
index++;
}
} } 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:
java Copy code for (type declaration : structure) { // statement one; // statement two; // … } Popcorn Hacks! Create an array, then use an enhanced for loop to print out each element of the array:
java Copy code /* Popcorn hacks go here */ public class Main { public static void main(String[] args) { // Create an array of integers int[] numbers = {1, 2, 3, 4, 5}; for (int number : numbers) { System.out.println(number); } } } 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 take a parameter of an array of primitive values (int or double) and return the item that is at the appropriate extreme.
Inside the method, a local variable is needed to store the current max or 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.
java Copy code import java.util.List;
public class MaxMinOfTwoLists {
public static void main(String[] args) {
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
List<Double> doubleList = Arrays.asList(1.5, 2.5, 3.5, 4.5, 5.5);
// Initialize variables to store the max and min of each list.
int intMax = intList.get(0);
int intMin = intList.get(0);
double doubleMax = doubleList.get(0);
double doubleMin = doubleList.get(0);
// Iterate over each list and update the max and min variables accordingly.
for (Integer intElement : intList) {
if (intElement > intMax) {
intMax = intElement;
}
if (intElement < intMin) {
intMin = intElement;
}
}
for (Double doubleElement : doubleList) {
if (doubleElement > doubleMax) {
doubleMax = doubleElement;
}
if (doubleElement < doubleMin) {
doubleMin = doubleElement;
}
}
// Print the max and min of each list.
System.out.println("max and min of the int list are: " + intMax + " " + intMin);
System.out.println("max and min of the double list are: " + doubleMax + " " + doubleMin);
} } Hacks! (Due 10/22 11:59 PM) 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:
arduino Copy code 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 For extra, create your own fun program using an array
java Copy code import java.util.Arrays; import java.util.Scanner;
public class StatsCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = scanner.nextInt();
}
// Sort the array to easily find A and C
Arrays.sort(arr);
int A = arr[N - 1]; // Maximum
int B = arr[0]; // Minimum
double C; // Median
if (N % 2 == 0) {
// If N is even, calculate the average of the middle two values
int mid1 = arr[N / 2 - 1];
int mid2 = arr[N / 2];
C = (double) (mid1 + mid2) / 2;
} else {
// If N is odd, take the middle value
C = (double) arr[N / 2];
}
// Perform the calculations
double calc1 = A + B + C;
double calc2 = A - B - C;
double calc3 = (A + B) * C;
// Print the results
System.out.println(calc1 + " " + calc2 + " " + calc3);
} } Extra java Copy code import java.util.Scanner;
public class FunArrayProgram { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int sumEven = 0;
long productOdd = 1; // Use long to avoid integer overflow
int largest = arr[0];
int smallest = arr[0];
for (int num : arr) {
if (num % 2 == 0) {
// Sum of even numbers
sumEven += num;
} else {
// Product of odd numbers
productOdd *= num;
}
// Find the largest and smallest numbers
if (num > largest) {
largest = num;
}
if (num < smallest) {
smallest = num;
}
}
System.out.println("Sum of even numbers: " + sumEven);
System.out.println("Product of odd numbers: " + productOdd);
System.out.println("Largest number: " + largest);
System.out.println("Smallest number: " + smallest);
} }