array
1
Chapter Objectives
Learn about arrays. Explore how to declare and manipulate data into arrays. Understand the meaning of array index out of bounds. Become familiar with the restrictions on array processing. Discover how to pass an array as a parameter to a method. Discover how to manipulate data in a twodimensional array. Learn about multidimensional arrays.
array
2
variables before we can print it in reverse order Let see the following code. (next slide).
array
import java.util.*; public class ReverseOrder { public static void main(String [] args) { int item0, item1, item2, item3, item4; int sum; Scanner input = new Scanner(System.in); System.out.println("Enter five integers one number per line"); item0 item1 item2 item3 item4 = = = = = input.nextInt(); input.nextInt(); input.nextInt(); input.nextInt(); input.nextInt();
sum = item0 + item1 + item2 + item3 + item4; System.out.println("The sum of the numbers = " + sum); System.out.println("The numbers in reverse order are: "); System.out.println(item4 + " " + item3 + " " + item2 + " " + item1 + " " + item0); } }
array
continue
We need 5 variables to hold the data
What happen if we want to read 100 (or more) numbers and print them in reverse order.
So, we need 100 variables to hold all data. (item0, item1, item2, item3, item4, item5,100) For large of data, this code is not desirable.
We need an ARRAY.
5
array
What is Array
A structured data type with a fixed number of
components.
Every component is of the same type. Components are accessed using their relative
One-Dimensional Arrays
Syntax to declare an array:
<dataType>[] <arrayName> = new <dataType>[intExp]; Or
Example
int[] num = new int[5]; or int num[] = new int[5];
This statement declare and creates the array num of 5 components. Each component is int data type
The components are num[0], num[1], num[2], num[3], num[4]
num
continue
element index
Continue
Array of five integers called test
test[0] = 85; test[1] = 98; test[2] = 75; test[3] = 87; test[4] = 68;
array
10
will store 10, 45 and 35 into the array in list[3], list[5] and list[6] respectively. (see next figure)
array
11
array
12
is called dynamic array Enables user to specify the size of the array
int arraySize; System.out.print("Enter the size of the array: "); arraySize = input.nextInt(); int[] list = new int[arraySize];
This statement creates the array list of six components and initializes the components using the values given. Here list.length is 6.
array
15
ways: 1. Initialing an array to a specific value 2. Input data into an array 3. Printing an array 4. Find the sum and average of an array 5. Determine the largest element in the array
array
16
array
17
3. Printing an array
double[] sales = new double[10]; int index; for(index = 0; index < sales.length;index++) System.out.print(sales[index] + " ");
array
18
array
19
double[] sales = new double[10]; int index, maxIndex; double largestSale; maxIndex = 0; for(index = 1; index<sales.length;index++) if (sales[maxIndex] < sales[index]) maxIndex = index; largestSale = sales[maxIndex];
array
20
continue
Suppose the array sales is as figure 9.5
array
21
i. ArrayIndexOutOfBoundsException exception is thrown. ii. The program will terminates with an appropriate error message
array
22
example
Consider the following declaration:
double[] num = double[10]; int i;
When i < 0 or i >= 10, the component num[i] is invalid (the index is out of bounds)
array
23
Consider the following loops for (i = 0; i <= 10; i++) list[i] = 5; When i = 10; list[i] = list[10] = 5; The program tries to access list[10] but does not exist We say the index is out of bound
list[0]
5 5 5 5 5 5 5 5 5
24
array
array
25
Searching a value
Eg.- A method to search an array of integer The Search method return the location of the first array element equal to the search value
searchValue = 60; int[] num = {10,20,30,40,50,60,70,80,90,100}; int location; for (int i=0; i < num.length; i++) if(num[i] = = searchValue) location = i;
array
26
Location, i
array
27
Calculation in array
Eg:- add a number from Array1 and Array2, and store the total in Array3 Assume Array1, Array2 and Array3 declarations as below: int[ ] Array1 = {10,20,30,40,50,60,70,80,90,100}; int[ ] Array2 = {11,22,33,44,55,66,77,88,99,110};
10 20 30 40 50 60 70 80
11 22 33 44 55 66 77 88
21 42 63 84 : : : :
Array[8] Array[9]
: :
29
public static void ArraySum() { int[] Array1 = {10,20,30,40,50,60,70,80,90,100}; int[] Array2 = {11,22,33,44,55,66,77,88,99,110}; int[] Array3 = new int[10]; Output int i; for (i=0; i < 10; i++) { Array3[i] = Array1[i] + Array2[i]; System.out.println("Array3["+i+"]= +Array3[i]); } }
Array3[0] = 21
Array3[1] = 42 Array3[2] = 63 Array3[3] = 84
Array3[4] = 105
Array3[5] = 126 Array3[6] = 147 Array3[7] = 168 Array3[8] = 189 Array3[9] = 210
array
30
for (i=0; i < 10; i++) Array3[i] = Array1[i] + Array2[i]; Values of Array3 during for loop iterations
i 0 Array1[i] 10 Array2[i] 11 Array3[i] 21
1
2 3 4 5 6 7 8 9
20
30 40 50 60 70 80 90 100
array
22
33 44 55 66 77 88 99 110
42
63 84 105 126 147 168 189 210
31
Reverse element
Eg- Read 10 integer numbers, and print the numbers in reverse order
public static void ReverseOrder() { int item[] = new int[10]; int i; //Read integers number and store in item[i] System.out.println("Enter ten integers number:"); for(i = 0; i < 10; i++) item[i] = input.nextInt(); //Print the output in reverse order are:"); System.out.println("The numbers in reverse order are:"); for(i = 9; i >= 0; i--) System.out.println(item[i]); }
array
32
Output
Enter ten integers number: 56 65 67 43 64 76 39 77 47 84 The numbers in reverse order are: 84 47 77 39 76 64 43 67 65 56 array
33
The above method have 3 formal parameters listA, listB and num
array
34
continue
Suppose we have the following statement
int[] intList = new int[10]; double[] doubleNumList = new double[15]; int number;
Actual parameter
array 35
example 1
public class PassingParameter { public static void main(String[] args) { int num[] = {10,20,30,40,50,60,70}; System.out.println( The number of elements: + num.length); printArray(num); Passing parameter }
public static void printArray(int[] number) { for (int index = 0; index < number.length; index++) System.out.println(number[index] + ""); } }
"
OUTPUT:
10 20 30 40 50 60
array
70
36
example 2
public static void main(String[] args) { int[] listA = {11,22,36,42,15,46,27,48,19,10} int[] listB = new int[10]; int Total, Largest; // call sumArray method and return a value to Total Total = sumArray (listA, listA.length); System.out.println(\n The sum of ListA is : + Total); // call indexLargestElement and return the indux value to Largest
array
continue
37
public static int sumArray(int[] list, int noOfElements) { int index; int sum = 0; for (index = 0; index < noOfElement; index++) sum = sum + list[index]; return sum; } public static int indexLargestElement(int[] list, int noOfElement) { int index; int maxIndex = 0; for (index = 1; index < noOfElement; index++) if(list[maxIndex] < list[index]) maxIndex = index; return maxIndex; }
array
38
array
39
Array of Object
Can use arrays to manipulate objects. Example: Create an array named array1 with N object of type T:
T[] array1 = new T[N]
example
Input students information's (name,matric, age) into array and print out the output
class StudentInfo{ String name; String matric; int age;
}
import java.util.*; public class ArrayOfObj { int N = 3; StudentInfo[] student = new StudentInfo[N];
public static void main (String[] args) { int N = 3; int i; ArrayOfObj arr = new ArrayOfObj(); StudentInfo[] Std = new StudentInfo[N]; Std = arr.InputData(); arr.PrintInfo(Std); }
array
41
public StudentInfo[] InputData() int i; StudentInfo[] student = new StudentInfo[N]; System.out.println("\nEnter Students Information "); public void PrintInfo(StudentInfo[] Std) { int i; System.out.println("List of students :\n");
for (i=0;i<N;i++)
{ System.out.println((i+1) + ". " + Std[i].matric + " " + Std[i].name + " " + " " + Std[i].age);
student[i].name = input.readLine();
System.out.print("Matric No : "); student[i].matric = input.nextLine(); System.out.print("Age : ");
}
}
array
42
output
Enter Students Information ___________________________ Name : BAHARUDIN OSMAN
Matric No : S34213 Age List of students : 1. S11111 BAHARUDIN OSMAN 2. S23212 BADRUL HAZMI 3. S34213 NUR BADRINA
array
: 27
30 28 27
43
array
44
array
45
Continue
array
46
Two-Dimension Array
A collection of a fixed number of components arranged in rows and columns. All components are in same type. Data is sometimes in table form (difficult to represent using a one-dimensional array).
10 20 30 40 50 60 70 80 90
11 22 33 44 55 66 77 88 99
45 34 21 32 13 21 33 22 123
array
47
continue
intRow => number of rows intCol => number of columns intRow and intCol > 0
Eg.
double[ ][ ] sales = new double[10][15];
array
48
array
49
To access a component of a two-dimensional array: arrayName[indexExp1][indexExp2]; indexExp1 = row position indexEXp2 = column position
Eg.
The above statement stores 25.75 into row number 5 and column number 3; (the 6th row and the 4th column)
array
50
array
51
array
52
eg.
Initialization Print Input data/store data into 2-Dimensional array Sum the data Find the largest element
Initialization
for (row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = 10;
matrix
array
54
Print
for (row = 0; row < matrix.lenth; row++) { for ( col = 0; col < matrix[row].length; col++) System.out.println(matrix[row][col]); System.out.println(); }
Read Data
for (row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = Integer.parseInt(keyboard.readLine())
array
55
Sum by Row
for (row = 0; row < matrix.length; row++) { sum = 0; for (col = 0; col < matrix[row].length; col++) sum = sum + matrix[row][col]; System.out.println(Sum of row + (row + 1) + = + sum); }
Sum by Column
for (col = 0; col < matrix[0].length; col++) { sum = 0; for (row = 0; row < matrix.length; row++) sum = sum + matrix[row][col]; System.out.println(Sum of column + (col + 1) + =+ sum);
array
56
array
57
Multidimensional Arrays
Can define three-dimensional arrays or n-dimensional arrays (n can be any number). Syntax to declare and instantiate array: dataType[][][] arrayName = new dataType[intExp1][intExp2][intExpn];
intExp1, intExp2, ..., intExpn = positive integers indexExp1,indexExp2, ..., indexExpn = nonnegative integers
array
58
double[][][] carDealers = new double[10][5][7]; for (i = 0; i < 10; i++) for (j = 0; j < 5; j++) for (k = 0; k < 7; k++) carDealers[i][j][k] = 10.00;
array
59