Chapter 5: Arrays
Arrays is one of the simplest data structure in JAVA. It is used to store data in a cell-like manner. The array’s cell starts from 0 to … as the following example will show:
Name of array: A
4 / 7 / 8 / 3 / 9 / 25 / 31 / 2 / 10 1 2 3 4 5 6 7 8 Array index
The index of the array let you manipulate the array i.e. retrieve data and store data in the array.
An array can be of any data type: integer, double, character, and objects like string, etc. Arrays are ideal to hold data as in a database. One important aspect of arrays is that it must only contain a single data type. That is if an array is declared to be of type integer, then only integer data type must be stored inside the array. To create an array, we need to declare it bearing in mind the type of data we would be storing inside of the array. For example if we want an array to store integer numbers, we would declare an array as follows:
int a[];
and now declare the size of the array as follows(if we wanted 10 elements in the array):
a = new int[10];
Note: we could have made a single declaration as follows:
int[] a = new int[10]; OR
int n = 10;
int[] a = new int[n];
Also, the value in the square brackets could be any expression that must evaluate to an integer.
We could have also initialized the array when it was declared:
int[] a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Similarly, we could have declared a string array as follows:
String name[];
OR and initialize it immediately.
String[] name = {"john"};
Array Subscripting:
As shown above, each element of an array has an index. It is this index that is used to retrieve or store data in that particular location. The indexing starts from 0 and goes to the full size of the array minus 1. The subscripting of an array is written as:
a[i] where a is the name of the array and i is any integer value or any
expression that must evaluate to an integer value.
To initialize an array, we could accomplish this in two ways. If we know the values we want to initialize the array with, we could do so when we declare the array, as shown above. If we do not know the values, then we would need to use a loop to do so. We could either use a while loop or a for loop to do so. In either case, we would need to know what the length of the array is. To find the length of the array, we could either use the value that was used when the array was declared or we could use the length function. We must note however, that when we are using the length function, we would not place the brackets at the end of length as we would normally do when we call functions. The following example shows the correct way first and the wrong way second:
int x = a.length;
NOT
int x = a.length();
First using a while loop with an array:
The following program will demonstrate the use of the while loop to create an array and then access the data of the array:
import jpb.*;
public class AverageGrade
{
public static void main(String[] args)
{
int i, sum, numberOfGrades;
String userInput;
int grades[];
SimpleIO.prompt("Enter the number of grades you want to average: ");
userInput = SimpleIO.readLine().trim();
numberOfGrades = Integer.parseInt( userInput);
grades = new int[numberOfGrades];
//int[] grades = new int[numberOfGrades];
i = 0;
while (i < grades.length)
{
SimpleIO.prompt("Enter grade #" + (i + 1) + ": ");
userInput = SimpleIO.readLine().trim();
grades[i] = Integer.parseInt( userInput);
i++;
}
sum = 0;
i = 0;
while (i < grades.length)
{
sum += grades[i];
i++;
}
System.out.println("\nThe average of the grades you have entered is: " +
sum/grades.length);
}
}
The for Loop:
This loop is used mainly for counting or to process a data structure whose size (length) is known or could be obtained by using a function call that will return the size (length) of the data structure.
A for loop has the following format:
for (initialization; test condition for exiting the loop; updating)
Note: If the test condition evaluates to true, then you would enter the loop and carry
out the statements. Else, you would exit the loop.
A for loop can have all three of these conditions inside of the parenthesis or none or any combination. However, the semi-colons present inside of the parenthesis regardless of how many parameters are used. Also if these conditions do not exist inside of the parenthesis, they must be found inside of the “for block”.
Also note that if there is no exit condition, or the exit condition cannot be evaluated properly, you would have an infinite loop (something that you do not want).
Example:
int n = 20;
for (int i = 0; i < n; i++)
System.out.println(i);
This loop will execute for 20 times – starting from 0 to 19. So the output of this slice of code would be a list of numbers starting from 0 and going to19.
OR (using block in for loop)
int n = 20, j = 0, k = 0;
for (int i = 0; i < n; i++)
{
j = i * i;
k = Math.pow(j, 2);
System.out.println(“The results are: “ + i + “ , “ + k);
}
For loops can also be nested. Example: Selection Sort:
import java.io.*;
public class sorting
{
public static void main(String[] args)
{
int num[] = {22,5,67,98,45,32,101,99,73,10};
int i, j, temp, min, minindex, moves1, moves2, comp;
moves1 = 0;
moves2 = 0;
comp = 0;
for(i = 0; i < 9; i++)
{
min = num[i];
minindex = i;
for(j = i + 1; j < 10; j++)
{
if (num[j] < min)
{
min = num[j];
minindex = j;
moves1++;
}
comp++;
}
if (min < num[i])
{
temp = num[i];
num[i] = min;
num[minindex] = temp;
moves2++;
}
comp++;
}
System.out.println("The sorted list is : ");
for (i = 0; i <= 9; i++)
System.out.print (num[i] + " ");
System.out.println();
System.out.println("The number of inner moves : " + moves1);
System.out.println("The number of comparisons : " + comp);
System.out.println("The number of outer moves : " + moves2);
}
}
Accessing Array Elements:
Two ways to access array elements: 1. Sequentially and 2. Randomly.
1. Sequentially: Going through the array element by element using either a for loop or a while loop. Example: The following loop searches an array name “array” for the first occurrence of the number 100 and then break out of the loop.
int i;
for (i = 0; i < array.length; i++)
if (array[i] == 100)
break;
Of course, we may add a little bit more code to this example to
produce some sort of a result.
2. Randomly: Being able to access any element of the array regardless of that element’s index location. Example array[10] or array[20] or the example program.
Arrays as vectors:
We could use arrays as vectors which would eventually let us use arrays to create matrices and other multidimensional data structures.
We could scale an array (vector) by multiplying that array with a constant value, Add two arrays and compute the dot product of two arrays. All of these could be done with the use of a for loop.
Arrays as database:
Using parallel arrays to create a database. NOT A GOOD IDEA. The best structure to use is an array of objects.
Example: We could modify the Account class of page 92 to give a BankAccount class
where the constructor could create objects with more than one parameter.
Public class BankAccount
{
private String lName, fName, address, accountNumber;
private double initialBalance;
public BankAccount(String x, String y, String z, double a)
{
lName = x;
fName = y;
accountNumber = z;
initialBalance = a;
}
OR
public BankAccount()
{
lName = “Doe”;
fName = “John”;
accountNumber = “000-000-000”;
initialBalance = 0.0;
}
To create an array of objects: i.e. an array with 100 objects.
BankAccount[] accounts = new BankAccount[100];
Note: The actual value in the array will be addresses to where these objects can be located.
Adding a record to the DataBase:
If int numAccounts = 0;
accounts[numAccounts] = new BankAccount(“Brown”, “Jane”, “111-222-333”, 1000.00);
numAccounts++;
4