You are on page 1of 43

array

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
two-dimensional array.
• Learn about multidimensional arrays.

array 2
What is Array?
Arrays are objects that help us organize large amounts
of information of the same type

An array is an ordered list of values


Array name scores
0 1 2 3 4 5 6 7 8 numeric
9 index

79 87 94 82 67 98 87 81 74 Array
91 elements
scores

A value is referenced by: scores[2] = 94

Array element can be used just like any other variable:

scores[2] = 89;
scores[n] = scores[n] + 2;
System.out.println ("Top = " + scores[5]);
Why need array?
consider the problem of writing a Java program: read 5 numbers, find the
sum, and prints them in reverse order

import java.util.*;
public class ReverseOrder
ta
the da
{
public static void main(String [] args) to h old
{ 5 va riables
d
int item0, item1, item2, item3, item4; We nee 000 data?
f1
int sum; What i
Scanner input = new Scanner(System.in);

System.out.println("Enter five integers one number per line");

item0 = input.nextInt();
item1 = input.nextInt();
item2 = input.nextInt();
item3 = input.nextInt();
item4 = 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);
}
}
Declaring Array
One-Dimensional Arrays

<dataType>[] <arrayName> = new <dataType>[intExp];


Or
<dataType> <arrayName>[]= new <dataType>[intExp];

1. dataType : a type of data will be store in array or component type


2. arrayName : a reference variable for array
3. intExp : size of an array (> 0)

int[] num = new int[5]; array Some examples


int num[] = new int[5]; subscripting
operator float[] prices = new float[500];

num boolean[]flags;
flags = new boolean[20];

char[] codes = new char[1750];


Examples of Array
Array of five Array of five
Array of five integers characters pointers called
called test called grade grade

test[0] = 85; grade[0] = ‘B’;


test[1] = 98; grade[1] = ‘C’;
test[2] = 75; grade[2] = ‘B’;
test[3] = 87; grade[3] = ‘A’;
test[4] = 68; grade[4] = ‘C’;
Assign value into
array
int[] list = new int[10];

Assume the declaration as above,


then
list[3] = 10;
list[6] = 35;
list[5] = list[3] + list[6];
10, 45 and 35 into the array in
list[3], list[5] and list[6]
respectively.
Dynamic Array
Array that are created during program
execution

Adv: Enables user to specify the size of the


array

int arraySize;
System.out.print("Enter the size of the array: "); the value of
arraySize = input.nextInt(); arraysize used to
instantiate the
int[] list = new int[arraySize]; object list
Initialization During
Declaration
Value can be assigned into the array during declaration

double[]sales = {12.25, 32.50, 16.90, 23.00, 45.68};

The size of the array is


determined by the number of
initial values within the braces.

If an array is declared and


initialized simultaneously, we
do not use the operator new to
instantiate the array object.
Instance Variable length
A public instance variable length is associated
with each array that has been instantiated.

The variable length contains the size of the array and can be
directly accessed in a program using array name and dot
operator.

int[] list = {10, 20, 30, 40, 50, 60};

Here list.length is 6.
Loops and Arrays
Loops can manipulate array by:

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
1. Initializing an array to a specific value
eg. to initialize every component of the array sale with a value of 10.00

double[] sales = new double[10];


int index;

for (index = 0; index < sales.length;index++)


sales[index] = 10.00;

2. Input data into an array

double[] sales = new double[10];


int index;

for (index = 0; index < sales.length;index++)


sales[index] = input.nextDouble();
3. Printing an array

double[] sales = new double[10];


int index;

for(index = 0; index < sales.length;index++)


System.out.print(sales[index] + " ");

4. Find the sum and average of an array


double[] sales = new double[10];
int index, sum;
double average;

sum = 0;
for(index = 0; index < sales.length;index++)
sum = sum + sales[index];

if (sales.length != 0)
average = sum / sales.length;
else
average = 0.0;
5. Determining the largest element in the array
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];
Index Out of Bounds
• An array is in bounds if:

0 <= index <= arraySize – 1

• An array is in out bounds if:

index < 0 or index > arraySize

If an array is out of bounds;

ArrayIndexOutOfBoundsException exception is thrown. The


program will terminates with an appropriate error message
Example
double[] num = double[10];
int i;

Consider the following loops


list[0] 5
for (i = 0; i <= 10; i++) list[1] 5
list[i] = 5; list[2] 5
list[3] 5
When i = 10; list[i] = list[10] = 5; list[4] 5
The program tries to access list[10]
list[5] 5
but does not exist  index is out of bound
list[6] 5
list[7] 5
list[8] 5
list[9] 5

ERROR
Using arrays
Searching a value

int Search (int[ ] num, int search value){


int location;
for (i=0; i =num.length; i++) method return the
if(num[i] = = search Value) location of the first
location = i; array element equal
return location; to the search value
}

num[0] 10
e.g. num[1] 20
num[2] 30
int[] num = {10,20,30,40,50,60,70,80,90,100}
num[3] 40
num[4] 50
searchValue is 60, the method will return 5 num[5] 60
num[6] 70
Return num[7] 80
Location, i num[8] 90
num[9] 100
e.g:- add a number from Array1 10 11
Calculation in arrayand Array2, store total in Array[0] Array[0]
Array3 Array[1] 20 Array[1] 22
Array[2] 30 Array[2] 33
Array[3] 40 Array[3] 44
Array[4] 50 Array[4] 55
int[ ] Array1 = {10,20,30,40,50,60,70,80,90,100};
Array[5] 60 + Array[5] 66
int[ ] Array2 = {11,22,33,44,55,66,77,88,99,110};
Array[6] 70 Array[6] 77
int[ ] Array3 = new int[10];
Array[7] 80 Array[7] 88
Array[8] 90 Array[8] 99
public static void ArraySum() Array[9] 100 Array[9] 110
{
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];
int i; Array[0] 21
Array[1] 42
for (i=0; i < 10; i++)
Array[2] 63
{
Array3[i] = Array1[i] + Array2[i]; Array[3] 84
Array[4] :
System.out.println("Array3["+i+"]=“ Array[5] :
+Array3[i]); Array[6] :
}
Array[7] :
}
Array[8] :
Array[9] :
Eg- Read 10 integer numbers,
Reverse and print the numbers in
element reverse order

Enter 10 nums:
public static void ReverseOrder() 56
{ 65
67
int item[] = new int[10];
43
int i; 64
//Read integers number and store in item[i] 76
System.out.println("Enter ten integers number:"); 39
for(i = 0; i < 10; i++) 77
item[i] = input.nextInt(); 47
84
After reversing:
//Print the output in reverse order are:"); 84
System.out.println("The numbers in reverse order are:"); 47
for(i = 9; i >= 0; i--) 77
System.out.println(item[i]); 39
} 76
64
43
67
65
56
Arrays as Parameters
Arrays can be passed as parameter to methods

public static void arrayAsFormalParameter(int[] listA,double[] listB, int num)


{
//…
}

Formal parameter
Suppose we have the following statement

int[] intList = new int[10];


double[] doubleNumList = new double[15];
int number;
Actual parameter
Statement to call the method

arrayAsFormalParameter(intList, doubleNumList, number);


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: " OUTPUT:
+ num.length);
The number of 
printArray(num); elements:  7
} Passing parameter
10
public static void printArray(int[] number) 20
{ 30
for (int index = 0; index < number.length; index++)
40
System.out.println(number[index] + "");
} 50
} 60
70 
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

indLargest = indexLargestElement (listA, list.length);


System.out.println(“\n The largest element is :” + listA[Largest]);

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 of String Objects
String[] nameList = new String[5]

nameList[0] = “Amanda Green”;


nameList[1] = “Vijay Arora”;
nameList[2] = “Sheila Mann”;
nameList[3] = “Rohit Sharma”;
nameList[4] = “Mandy Johnson”;
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] Instantiatio
for(int j=0; j < array1.length; j++) n
eg. a) clock – hour, minute, second
array1[j] = new T();
b) student – name, matric, age

Example
class StudentInfo{
Input students String name;
information's String matric;
int age;
(name,matric, age) into }
array and print out the
output 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);
}
public StudentInfo[] InputData() int i;
StudentInfo[] student = new StudentInfo[N];
System.out.println("\nEnter Students Information ");
System.out.println("___________________________ \n");
for (i = 0; i< N; i++)
{
student[i] = new StudentInfo();
System.out.print("Name : ");
student[i].name = input.readLine();
System.out.print("Matric No : ");
student[i].matric = input.nextLine();
System.out.print("Age : ");
student[i].age = input.nextInt();
System.out.println();
}
return student;
}

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);
}
}
output

Enter Students Information  
___________________________ 
 Name        : BAHARUDIN OSMAN
 Matric No  : S11111
 Age           : 30
 Name         : BADRUL HAZMI   
 Matric No   : S23212
 Age           : 28
 Name          : NUR BADRINA    
 Matric No   : S34213
 Age           : 27
 List of students :
 1. S11111  BAHARUDIN OSMAN    30 
 2. S23212  BADRUL HAZMI       28 
 3. S34213  NUR BADRINA        27 
array of object
create an array of arrivalTimeEmp

Clock[] arrivalTimeEmp = new Clock[100];


Instantiating of Array Objects

for (int j = 0; j < arrivalTimeEmp.length; j++)


arrivalTimeEmp[j] = new Clock();

array 28
Setting a time for index 49

arrivalTimeEmp[49].setTime(8, 5, 10);
Delete Object

i. Identify the element to delete


ii. Point the object to delete null
iii. Move up all elements (after deleted object)
iv. Point the last element to null

Example
 Step 1 : Identify the element to delete
 Step 2 : Point the object to delete to null for (i=0; i < student.length; i++)
- if the sixth element to delete if(i==5) then
student[i] = null

student Name
Matric
IC

null
Name
Matric
IC
iii. Move up all elements (after deleted object)
iv. Point the last element to null

student student

for (i = 0; i < student.length; i++) [0] element A


[0] element A
if (i= =5) [1] [1]
element B element B
student[i] = student[student.length -1)
if (i= = (student.length – 1)) [2] element C [2] element C
student[i] = null [3] [3]
element D element D

[4] element E [4] element E

[5] element [5] element G

[6] element G [6] element H


Set the last element to null element H element I
[7] [7]
element I element J
[8] [8]
element J
[9] [9]

before after null


array 31
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 11 21 45
20 22 42 34
30 33 66 21
40 44 84 32
50 55 105 13
60 66 126 21
70 77 147 33
80 88 168 22
90 99 189 123

array 32
continue

• To declare/instantiate a two-dimensional array:

dataType[ ][ ] arrayName = new data Type[intRow][intCol];

intRow => number of rows


intCol => number of columns

intRow and intCol > 0


• Eg.
double[ ][ ] sales = new double[10][15];

array 33
double[ ][ ] sales = new double[10][5];

array 34
Accessing Array Components

 To access a component of a two-dimensional array:


arrayName[indexExp1][indexExp2];

indexExp1 = row position


indexEXp2 = column position
 Eg.

sales [5][3] = 25.75;

 The above statement stores 25.75 into row number 5 and column
number 3; (the 6th row and the 4th column)

array 35
Sales [5][3] = 25.75;

array 36
Array Initialization During Declaration
 2-Dimensional array can be initialized during declaration
 Eg.

int[ ][ ] board = { {2,3,1},


{15,25,13},
{20,4,7},
{11,18,14}};

array 37
Processing 2-Dimensional Array

 eg.
• Initialization
• Print
• Input data/store data into 2-Dimensional array
• Sum the data
• Find the largest element

 Suppose the declaration as below:

int row;

int column;

int matix = new int[7][6];


array 38
Initialization
for (row = 0; row < matrix.length; row++)
for (col = 0; col < matrix[row].length; col++)
matrix[row][col] = 10;

matrix

array 39
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 40
Largest Element in Each Row

for (row = 0; row < matrix.length; row++)


{
largest = matrix[row][0];
for (col = 1; col < matrix[row].length; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
System.out.println(“The largest element of row” + (row+1)
+ “=“ + largest);
}

array 41
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];

 Syntax to access component:


arrayName[indexExp1][indexExp2]…[indexExpn]

 intExp1, intExp2, ..., intExpn = positive integers


 indexExp1,indexExp2, ..., indexExpn = non-
negative integers

array 42
Loops to Process Multidimensional Arrays

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;

You might also like