SlideShare ist ein Scribd-Unternehmen logo
1 von 61
array 1
Array
array 2
• 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.
Chapter Objectives
array 3
Why do need array
• Let consider the following problem
How do we write Java program that read five
numbers, find the sum, and prints the numbers
in reverse order
• Normally, we need to store all the numbers in 5
variables before we can print it in reverse order
• Let see the following code. (next slide).
array 4
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 = 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);
}
}
array 5
• 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.
continue
array 6
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
positions in the array.
• Types of array
- One-Dimensional array
- Two-Dimensional array
- Multi Dimensional array
array 7
One-Dimensional Arrays
• Syntax to declare an array:
<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)
• Syntax to access an array component:
- arrayName[indexExp]
array 8
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]
• The value in square bracket [ ] is
call index and it start at 0
num
array 9
continue
element
index
In java, [ ] is call as array subscripting operator
Items in an array is called elements
array 10
Continue
Array of five
integers called test
Array of five
characters
called grade
test[0] = 85;
test[1] = 98;
test[2] = 75;
test[3] = 87;
test[4] = 68;
grade[0] = „B‟;
grade[1] = „C‟;
grade[2] = „B‟;
grade[3] = „A‟;
grade[4] = „C‟;
array 11
Assign a value into array
int[] list = new int[10];
Assume the declaration as above.
Statement;
list[3] = 10;
list[6] = 35;
list[5] = list[3] + list[6];
will store 10, 45 and 35 into the array in list[3],
list[5] and list[6] respectively. (see next figure)
array 12
array 13
Specifying Array Size During Program
Execution (dynamic array)
• Array that are created during program execution
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];
• The system use the value of arraysize to instantiate
the object list
array 14
Array Initialization During Declaration
• We also can assign a value into the array during declaration
double[]sales = {12.25, 32.50, 16.90, 23.00,
45.68};
• The values, called initial values, are placed
between braces and separated by commas
• When declaring and initializing arrays, 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.
array 15
Arrays and the 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.
• The variable length can be directly accessed in a
program using the array name and the dot operator.
int[] list = {10, 20, 30, 40, 50, 60};
•This statement creates the array list of six
components and initializes the components using the
values given.
• Here list.length is 6.
array 16
Loops and Arrays
• Loops can be used to process array in several
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 17
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;
array 18
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] + " ");
array 19
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;
array 20
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];
array 21
continue
Suppose the array sales is as figure 9.5
array 22
Array 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;
i. ArrayIndexOutOfBoundsException exception is thrown.
ii. The program will terminates with an appropriate
error message
array 23
example
Consider the following declaration:
double[] num = double[10];
int i;
• The component num[i] is valid if i = 0, 1, 2….9
• When i < 0 or i >= 10, the component num[i] is
invalid (the index is out of bounds)
array 24
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
5
5
5
5
5
5
5
5
5
5
list[0]
list[1]
list[2]
list[3]
list[4]
list[5]
list[6]
list[7]
list[8]
list[9]
array 25
Manipulate data into arrays
• Searching a value
• Calculation
• Reverse element
array 26
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
int Search (int[ ] num, int search value){
int location;
for (i=0; i =num.length; i++)
if(num[i] = = search Value)
location = i;
return location;
}
array 27
• Assume the num values as below:
int[] num = {10,20,30,40,50,60,70,80,90,100}
• If searchValue is 60, the
method will return 5 to Search
method.
40
10
20
30
50
60
70
80
90
100
num[0]
num[1]
num[2]
num[3]
num[4]
num[5]
num[6]
num[7]
num[8]
num[9]
Location, i
array 28
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};
int[ ] Array3 = new int[10];
array 29
+
10 21
42
63
84
:
:
:
:
:
:
11
20
30
40
50
60
70
80
90
100
22
33
44
55
66
77
88
99
110
Array[0]
Array[1]
Array[2]
Array[3]
Array[4]
Array[5]
Array[6]
Array[7]
Array[8]
Array[9]
Array[0]
Array[1]
Array[2]
Array[3]
Array[4]
Array[5]
Array[6]
Array[7]
Array[8]
Array[9]
Array[0]
Array[1]
Array[2]
Array[3]
Array[4]
Array[5]
Array[6]
Array[7]
Array[8]
Array[9]
array 30
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];
int i;
for (i=0; i < 10; i++)
{
Array3[i] = Array1[i] + Array2[i];
System.out.println("Array3["+i+"]=“
+Array3[i]);
}
}
Output
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 31
for (i=0; i < 10; i++)
Array3[i] = Array1[i] + Array2[i];
Values of Array3 during for loop iterations
i Array1[i] Array2[i] Array3[i]
0 10 11 21
1 20 22 42
2 30 33 63
3 40 44 84
4 50 55 105
5 60 66 126
6 70 77 147
7 80 88 168
8 90 99 189
9 100 110 210
array 32
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 33
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 34
Arrays as Formal Parameters to Methods
Arrays can be passed as parameter to methods
Eg.
public static void arrayAsFormalParameter(int[] listA,
double[] listB, int num)
{
//…
}
Formal parameter
The above method have 3 formal parameters – listA,
listB and num
Statement to call the method
array 35
arrayAsFormalParameter(intList, doubleNumList, number);
Actual parameter
int[] intList = new int[10];
double[] doubleNumList = new double[15];
int number;
Suppose we have the following statement
example 1
array 36
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);
}
public static void printArray(int[] number)
{
for (int index = 0; index < number.length; index++)
System.out.println(number[index] + "");
}
}
Passing parameter
OUTPUT:
The number of elements: 7
10
20
30
40
50
60
70
array 37
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]);
example 2
continue
array 38
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
array 39
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
array 40
• Can use arrays to manipulate objects.
• Example: Create an array named array1 with N
object of type T:
T[] array1 = new T[N]
• Can instantiate array1 as follows:
for(int j=0; j < array1.length; j++)
array1[j] = new T();
• Eg:
a) clock – hour, minute, second
b) student – name, matric, age
array 41
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);
}
example
Input students information's (name,matric, age) into array and print out the output
class StudentInfo{
String name;
String matric;
int age;
}
array 42
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);
}
}
array 43
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
output
Statement below create an array of arrivalTimeEmp
array 44
Clock[] arrivalTimeEmp = new Clock[100];
Instantiating of Array Objects
array 45
for (int j = 0; j < arrivalTimeEmp.length; j++)
arrivalTimeEmp[j] = new Clock();
Continue
array 46
• Setting a time for index 49
arrivalTimeEmp[49].setTime(8, 5, 10);
Delete Object
array 47
• Step
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
- if the sixth element to delete
array 48
for (i=0; i < student.length; i++)
if(i==5) then
student[i] = null
null
student
Name
Matric
IC
Name
Matric
IC
Name
Matric
IC
array 49
element A
element B
element C
element D
element E
element
element G
element H
element I
element J
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
element A
element B
element C
element D
element E
element G
element H
element I
element J
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
iii. Move up all elements (after deleted object)
iv. Point the last element to null
for (i = 0; i < student.length; i++)
if (i= =5)
student[i] = student[student.length -1)
if (i= = (student.length – 1))
student[i] = null
Set the last element to null
nullbefore
studentstudent
after
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 50
continue
array 51
• 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 52
double[ ][ ] sales = new double[10][5];
Accessing Array Components
 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 53
sales [5][3] = 25.75;
array 54
Sales [5][3] = 25.75;
Array Initialization During Declaration
 2-Dimensional array can be initialized during declaration
 Eg.
array 55
int[ ][ ] board = { {2,3,1},
{15,25,13},
{20,4,7},
{11,18,14}};
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:
array 56
int row;
int column;
int matix = new int[7][6];
array 57
Initialization
for (row = 0; row < matrix.length; row++)
for (col = 0; col < matrix[row].length; col++)
matrix[row][col] = 10;
matrix
array 58
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 59
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);
}
 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 60
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;
array 61
Loops to Process Multidimensional Arrays

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Array ppt
Array pptArray ppt
Array ppt
 
Array and string
Array and stringArray and string
Array and string
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
C functions
C functionsC functions
C functions
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
 
Algorithm analysis in fundamentals of data structure
Algorithm analysis in fundamentals of data structureAlgorithm analysis in fundamentals of data structure
Algorithm analysis in fundamentals of data structure
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Array in C
Array in CArray in C
Array in C
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Recursion
RecursionRecursion
Recursion
 
Recursion
RecursionRecursion
Recursion
 
Arrays
ArraysArrays
Arrays
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 

Ähnlich wie Array

Ähnlich wie Array (20)

Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
Array-part1
Array-part1Array-part1
Array-part1
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
array-191103180006.pdf
array-191103180006.pdfarray-191103180006.pdf
array-191103180006.pdf
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Arrays
ArraysArrays
Arrays
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Python array
Python arrayPython array
Python array
 
Week06
Week06Week06
Week06
 
Arrays
ArraysArrays
Arrays
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays
ArraysArrays
Arrays
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 

Mehr von PRN USM

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2PRN USM
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1PRN USM
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2PRN USM
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1PRN USM
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - IntroPRN USM
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition StructurePRN USM
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control StructuresPRN USM
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And ExpressionPRN USM
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and JavaPRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree HomesPRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean ExperiencePRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesPRN USM
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlPRN USM
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From MhpbPRN USM
 

Mehr von PRN USM (19)

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
 

Kürzlich hochgeladen

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 

Kürzlich hochgeladen (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 

Array

  • 2. array 2 • 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. Chapter Objectives
  • 3. array 3 Why do need array • Let consider the following problem How do we write Java program that read five numbers, find the sum, and prints the numbers in reverse order • Normally, we need to store all the numbers in 5 variables before we can print it in reverse order • Let see the following code. (next slide).
  • 4. array 4 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 = 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); } }
  • 5. array 5 • 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. continue
  • 6. array 6 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 positions in the array. • Types of array - One-Dimensional array - Two-Dimensional array - Multi Dimensional array
  • 7. array 7 One-Dimensional Arrays • Syntax to declare an array: <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) • Syntax to access an array component: - arrayName[indexExp]
  • 8. array 8 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] • The value in square bracket [ ] is call index and it start at 0 num
  • 9. array 9 continue element index In java, [ ] is call as array subscripting operator Items in an array is called elements
  • 10. array 10 Continue Array of five integers called test Array of five characters called grade test[0] = 85; test[1] = 98; test[2] = 75; test[3] = 87; test[4] = 68; grade[0] = „B‟; grade[1] = „C‟; grade[2] = „B‟; grade[3] = „A‟; grade[4] = „C‟;
  • 11. array 11 Assign a value into array int[] list = new int[10]; Assume the declaration as above. Statement; list[3] = 10; list[6] = 35; list[5] = list[3] + list[6]; will store 10, 45 and 35 into the array in list[3], list[5] and list[6] respectively. (see next figure)
  • 13. array 13 Specifying Array Size During Program Execution (dynamic array) • Array that are created during program execution 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]; • The system use the value of arraysize to instantiate the object list
  • 14. array 14 Array Initialization During Declaration • We also can assign a value into the array during declaration double[]sales = {12.25, 32.50, 16.90, 23.00, 45.68}; • The values, called initial values, are placed between braces and separated by commas • When declaring and initializing arrays, 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.
  • 15. array 15 Arrays and the 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. • The variable length can be directly accessed in a program using the array name and the dot operator. int[] list = {10, 20, 30, 40, 50, 60}; •This statement creates the array list of six components and initializes the components using the values given. • Here list.length is 6.
  • 16. array 16 Loops and Arrays • Loops can be used to process array in several 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
  • 17. array 17 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;
  • 18. array 18 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] + " ");
  • 19. array 19 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;
  • 20. array 20 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];
  • 21. array 21 continue Suppose the array sales is as figure 9.5
  • 22. array 22 Array 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; i. ArrayIndexOutOfBoundsException exception is thrown. ii. The program will terminates with an appropriate error message
  • 23. array 23 example Consider the following declaration: double[] num = double[10]; int i; • The component num[i] is valid if i = 0, 1, 2….9 • When i < 0 or i >= 10, the component num[i] is invalid (the index is out of bounds)
  • 24. array 24 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 5 5 5 5 5 5 5 5 5 5 list[0] list[1] list[2] list[3] list[4] list[5] list[6] list[7] list[8] list[9]
  • 25. array 25 Manipulate data into arrays • Searching a value • Calculation • Reverse element
  • 26. array 26 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 int Search (int[ ] num, int search value){ int location; for (i=0; i =num.length; i++) if(num[i] = = search Value) location = i; return location; }
  • 27. array 27 • Assume the num values as below: int[] num = {10,20,30,40,50,60,70,80,90,100} • If searchValue is 60, the method will return 5 to Search method. 40 10 20 30 50 60 70 80 90 100 num[0] num[1] num[2] num[3] num[4] num[5] num[6] num[7] num[8] num[9] Location, i
  • 28. array 28 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}; int[ ] Array3 = new int[10];
  • 30. array 30 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]; int i; for (i=0; i < 10; i++) { Array3[i] = Array1[i] + Array2[i]; System.out.println("Array3["+i+"]=“ +Array3[i]); } } Output 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
  • 31. array 31 for (i=0; i < 10; i++) Array3[i] = Array1[i] + Array2[i]; Values of Array3 during for loop iterations i Array1[i] Array2[i] Array3[i] 0 10 11 21 1 20 22 42 2 30 33 63 3 40 44 84 4 50 55 105 5 60 66 126 6 70 77 147 7 80 88 168 8 90 99 189 9 100 110 210
  • 32. array 32 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]); }
  • 33. array 33 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
  • 34. array 34 Arrays as Formal Parameters to Methods Arrays can be passed as parameter to methods Eg. public static void arrayAsFormalParameter(int[] listA, double[] listB, int num) { //… } Formal parameter The above method have 3 formal parameters – listA, listB and num
  • 35. Statement to call the method array 35 arrayAsFormalParameter(intList, doubleNumList, number); Actual parameter int[] intList = new int[10]; double[] doubleNumList = new double[15]; int number; Suppose we have the following statement
  • 36. example 1 array 36 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); } public static void printArray(int[] number) { for (int index = 0; index < number.length; index++) System.out.println(number[index] + ""); } } Passing parameter OUTPUT: The number of elements: 7 10 20 30 40 50 60 70
  • 37. array 37 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]); example 2 continue
  • 38. array 38 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; }
  • 39. Array of String Objects array 39 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”;
  • 40. Array of Object array 40 • Can use arrays to manipulate objects. • Example: Create an array named array1 with N object of type T: T[] array1 = new T[N] • Can instantiate array1 as follows: for(int j=0; j < array1.length; j++) array1[j] = new T(); • Eg: a) clock – hour, minute, second b) student – name, matric, age
  • 41. array 41 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); } example Input students information's (name,matric, age) into array and print out the output class StudentInfo{ String name; String matric; int age; }
  • 42. array 42 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); } }
  • 43. array 43 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 output
  • 44. Statement below create an array of arrivalTimeEmp array 44 Clock[] arrivalTimeEmp = new Clock[100];
  • 45. Instantiating of Array Objects array 45 for (int j = 0; j < arrivalTimeEmp.length; j++) arrivalTimeEmp[j] = new Clock();
  • 46. Continue array 46 • Setting a time for index 49 arrivalTimeEmp[49].setTime(8, 5, 10);
  • 47. Delete Object array 47 • Step 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
  • 48. Example  Step 1 : Identify the element to delete  Step 2 : Point the object to delete to null - if the sixth element to delete array 48 for (i=0; i < student.length; i++) if(i==5) then student[i] = null null student Name Matric IC Name Matric IC Name Matric IC
  • 49. array 49 element A element B element C element D element E element element G element H element I element J [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] element A element B element C element D element E element G element H element I element J [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] iii. Move up all elements (after deleted object) iv. Point the last element to null for (i = 0; i < student.length; i++) if (i= =5) student[i] = student[student.length -1) if (i= = (student.length – 1)) student[i] = null Set the last element to null nullbefore studentstudent after
  • 50. 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 50
  • 51. continue array 51 • 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];
  • 52. array 52 double[ ][ ] sales = new double[10][5];
  • 53. Accessing Array Components  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 53 sales [5][3] = 25.75;
  • 55. Array Initialization During Declaration  2-Dimensional array can be initialized during declaration  Eg. array 55 int[ ][ ] board = { {2,3,1}, {15,25,13}, {20,4,7}, {11,18,14}};
  • 56. 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: array 56 int row; int column; int matix = new int[7][6];
  • 57. array 57 Initialization for (row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = 10; matrix
  • 58. array 58 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())
  • 59. array 59 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); }
  • 60.  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 60 Multidimensional Arrays
  • 61. 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 61 Loops to Process Multidimensional Arrays