Arrays
Assumed Knowledge
Learning Outcomes
- Understand how to create, populate and operate on arrays <!–* how larger chunks of data are stored in a program
- Understand how to access these larger chunks of data
- Understand the most common data chunks, arrays–>
Arrays
An array is a fixed-sized collection of items, each item of the same type.
So you can have,
- an array of 5 integers
- an array of 20 booleans
- an array of 2000 characters
- an array of 50 Strings
- an array of 400 arrays
- and so on…
Perhaps The most important concept to understand in arrays is the difference between a reference and an instance.
Reference - the variable name by which you know the array
Instance - the actual collection of items to which a reference refers.
Syntax to create an array
There are a few ways to create an array.
Creating array - Option 1
The most common way to create an array is by specifying the type and size of the array.
1
type[] arrayName = new type[size];
NOTE: This only works when the array is first created (more on this later)
Example - integer array
1
int[] arr = new int[5]; //an array that holds 5 integers
Reference: arr
Instance: the block with 5 integer values
Example - boolean array
1
boolean[] flags = new boolean[4]; //an array that holds 4 booleans
reference: flags
instance: the block with 4 boolean values
Creating array - Option 2
When you know the values that need to be stored in the array beforehand, you can create an array as,
1
type[] arrayName = {item1, item2, ....};
Examples
1
int[] taxicab = {10, 70, 20, 90};
reference: taxicab
instance: the block with the integer values 10, 70, 20, 90
1
2
3
4
int[] cutoffs = {50, 65, 75, 85};
char[] punctuations = {'.', '!', '?', ',', ';', ':'};
double[] significantNumbers = {3.141, 1.618, 2.718, 57.295, 1.202, 1.414};
boolean[] twentyTwo = {true, false, true, true, false};
Size of an array
The number of items in an array arr
is given by arr.length
.
Note that, given what we said above this means .length
should be read as “follow the reference and see how large the chunk of memory at the other end is”.
For example,
1
2
int[] data = new int[20];
println(data.length); //displays 20
Accessing items of an array
- The first item of an array
arr
is at index 0. - The second item of an array
arr
is at index 1. - …
- The last item of an array
arr
is at indexarr.length - 1
.
Thus you can traverse an array using a loop from 0
to arr.length - 1
as,
1
2
3
for(int i=0; i < arr.length; i++) {
//do what you want with arr[i]
}
Example
Create an array that holds the outcome of 20 dice rolls.
Each dice roll is a random integer between 1 and 6.
1
2
3
4
int[] outcomes = new int[20];
for(int i=0; i < outcomes.length; i++) {
outcomes[i] = (int)random(1, 7); //remember 7 is not included
}
Then we can find out the average outcome as,
1
2
3
4
5
6
int total = 0;
for(int i=0; i < outcomes.length; i++) {
total += outcomes[i];
}
double average = (total * 1.0)/outcomes.length;
//multiplication with 1.0 to convert int to double
Re-referencing an array
Remember how we noted that the following only works when the array is FIRST created?
1
int[] taxi = {10, 70, 20, 90};
If we split this statement, it would be:
1
2
3
4
5
6
int[] taxi; //declaration - creates the reference
// following ATTEMPTS to link the reference to the instance.
// BUT SYNTACTICALLY INVALID
taxi = {90, 20, 70, 10}; //INCORRECT
Once an array reference is created, to re-reference it to a new instance, you have to use the following syntax:
1
arrayName = new Type[size];
or
1
arrayName = new Type[]{item1, item2, ...};
For example,
1
2
taxicab = {90, 20, 70, 10}; //INCORRECT
taxicab = new int[]{90, 20, 70, 10}; //CORRECT
1
2
3
4
boolean[] switches;
switches = {true, false, true}; //INCORRECT
switches = new boolean[]{true, false, true}; //CORRECT
You can also re-reference an array to another instance already created (and referenced by some other array). Here’s how…
Copying an array into another array
When an array, say src
, is copied into another array, say dest
, both references - src
and dest
- refer to the instance to which src
was originally referring.
1
2
int[] src = {10, 70, 20, 90};
int[] dest = src;
We call this a reference copy.
NOTE: The type of arrays must be the same. You cannot copy an int
array into a float
array. The following will not work:
1
2
int[] taxi = {10, 70, 20, 90};
float[] cab = taxi; //Compilation error!
Another example
1
2
3
4
int[] a = {70, 80, 60};
int[] b = {10, 70, 20, 90};
int[] c = a;
a = b;
- After the first line, there is one reference and one instance.
- After the second line, there are two references and two instances.
- After the third line, there are three references but still, only two instances. Currently,
a
andc
refer to the same instance.
- After the fourth line, there are three references but still, only two instances. Now,
a
andb
refer to the same instance.
Instance copy of an array
When you want to duplicate or clone an array, you can create an array of the same size as the original array, and copy all items over. This is known as instance copy.
1
2
3
4
5
6
7
8
int[] source = {10, 70, 20, 90};
//creating an instance copy of source into destination -
int[] destination = new int[source.length]; //same size as source
for(int i=0; i < source.length; i++) {
destination[i] = source[i];
}
Exercises
Exercise 1
Create the following arrays:
- An array
a
that has capacity for 2000 integers. - An array
b
that has capacity for 5000 characters. - An array
c
that has capacity for 666 booleans. - An array
d
that has capacity for 1 float. - An array
e
containing the values5, 6, 7, 8
. - An array
f
containing the valuesfalse, true, true
. - An array
g
containing the values'M', 'e', 's', 's', 'i'
. - An array
h
containing the values1.414, 7.2, -2.5, 9.81
.
Exercise 2
- Assume the existence of integer array
tom
and make a reference copy oftom
intojerry
. - Assume the existence of boolean array
aang
and make a reference copy ofaang
intokatara
as well astoph
.
Exercise 3
Draw the memory diagram for the following code,
1
int[] data = new int[]{50, 90, 30, 20, 60};
Exercise 4
Draw the memory diagram for the following code,
1
2
3
4
5
6
7
8
9
int[] data = new int[6];
for(int i=0; i < data.length; i++) {
if(i%2 == 0) {
data[i] = 2*i+1;
}
else {
data[i] = -3*i;
}
}
Exercise 6
List the references and instance created in the following code.
1
2
3
4
5
int[] a = {10, 70, 20, 90};
int[] b = a;
char[] c = {'h', 'e', 'y', '!'};
char[] d = c;
boolean b = new boolean[10];
Exercise 7
Explain why the following code will not compile.
1
2
3
int[] a = {10, 70, 20, 90};
int[] b = new int[10];
b[2] = a;
Exercise 8
Write a piece of code that creates the arrays represented in the following diagram.
Exercise 9
Write a piece of code that creates the arrays represented in the following diagram.
Exercise 10
Draw the memory diagram for the following code,
1
2
3
4
int[] a = {4,8,15,16,23,42};
int[] b = a;
b[2] = 100;
b = new int[]{104,101,108,108,111};
Exercise 11
Write a piece of code that creates an array with 100 integers, each between 1 and 20. Count the number of items that are divisible by the item after them.
For example, if the first few items of the array are {20, 5, 8, 4, 4, ...}
, 20 is divisible by 5, 8 is divisible by 4, and 4 is divisible by 4, so we have 3 such items so far.
Exercise 12
Consider the following piece of code.
1
2
3
4
5
int[] items = new int[10];
items[0] = 1;
for(int i=1; i < items.length; i++) {
items[i] = 2 * items[i-1];
}
What are the contents of the array items
?
Furthering your understanding
Coding in the real life
The ages of 20 people is stored in an array ageList
. Write a piece of code that determines the range of the distribution. That is, the age difference between the oldest and the youngest person.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//assuming ageList is a boolean array containing 20 items
int min = ageList[0];
for(int i=1; i < ageList.length; i++) {
if(ageList[i] < min) {
min = ageList[i];
}
}
int max = ageList[0];
for(int i=1; i < ageList.length; i++) {
if(ageList[i] > max) {
max = ageList[i];
}
}
int range = max - min;
The state of 25 electrical switches is held in an array smartSwitches
. The states can be “On” (true) or “Off” (false). Write a piece of code that toggles all switches. That is, all switches that are currently “On” should turn “Off”, and all switches that are currently “Off” should turn “On”.
Solution
1
2
3
4
5
//assuming smartSwitches is a boolean array containing 25 items
for(int i=0; i < smartSwitches.length; i++) {
smartSwitches[i] = !smartSwitches[i];
}
Assume that we are encoding birthdays as integers where:
- 1st january is 0,
- 2nd january is 1,
- and so on till,
- 31st december is 365
(remember that 29th february will also be given an integer mapping).
The birthdays of 1000 people is stored in an array bdays
. Write a piece of code that displays the most frequent date of birth. For the basic version, you may display an integer between 0 and 365. For the advanced version, display the actual data in DD/MM
format.
Solution
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
//assuming bdays is an array containing 1000 items
//such that each item is in range [0...365]
/*
frequencies holds number of birthdays on each of the 366 days.
if a birthday falls on 1st jan (coded as 0), frequencies[0] increases by 1
if a birthday falls on 2nd jan (coded as 1), frequencies[1] increases by 1
...
if a birthday falls on 32st dec (coded as 365), frequencies[365] increases by 1
*/
int[] frequencies = new int[366];
for(int i=0; i < bdays.length; i++) {
/*
int idx = bdays[i];
frequencies[idx]++; //another birthday on that day
}
int mostFrequentBday = 0; //1st jan
for(int i=1; i < frequencies.length; i++) {
if(frequencies[i] > frequencies[mostFrequentBday]) {
mostFrequentBday = i;
}
}
println(mostFreqBday);
//advanced:
int[] daysInMonths = {31,29,31,30,31,30,31,31,30,31,30,31};
int currentMonth = 0;
while(mostFreqBday < daysInMonths[currentMonth]) {
mostFreqBday = mostFreqBday - daysInMonths[currentMonth];
}
int dayInMonth = mostFreqBday+1;
println(dayInMonth+"/"+currentMonth);
I keep track of the time taken (in minutes) to run each kilometer over a 100km race (let me dream!). These times are stored in an array lapTimes
. For example, if lapTimes[0]
is 6.23, it means I ran the first kilometer in 6 minutes 13.8 seconds.
Write a piece of code that determines my fastest lap (for example, display “Kilometer 0-1” if the first kilometer was the fastest, and “Kilometer 63-64” if the 64th kilometer was the fastest.)
Solution
1
2
3
4
5
6
7
8
//assuming lapTimes is a float array containing 100 items
int fastestLap = 0;
for(int i=1; i < lapTimes.length; i++) {
if(lapTimes[i] < lapTimes[fastestLap]) {
fastestLap = i;
}
}
print("Kilometer "+fastestLap+"-"+(fastestLap+1));