Вы находитесь на странице: 1из 43

9.

Array

Knowledge:
Understand the execute technique of array
Skill:
Can write application program using one and two dimensional
array
Why Array?
Consider the following..(recall)

 Assume that you were asked to write a


program that accept 10 student marks,
calculating average mark, and then print out
number of students that get more than
average mark.
 How to store all these marks?

2 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Solution Without Array (1/6)
public class Average {
public static void main(String[] args) {
//variables declaration
int mark1,mark2,mark3,mark4,mark5;
int mark6,mark7,mark8,mark9,mark10;
int studentNumbers, totalMark;
float markAverage;
Scanner input = new Scanner(System.in);

Variables Declaration
3 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Solution Without Array (2/6)
//get student mark
System.out.print(“Mark 1:”);
mark1 = input.nextInt();
System.out.print(“Mark 2:”);
mark2 = input.nextInt();
System.out.print(“Mark 3:”);
mark3 = input.nextInt();
System.out.print(“Mark 4:”);
mark4 = input.nextInt();
System.out.print(“Mark 5:”);
mark5 = input.nextInt();

4
Get Inputs TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Solution Without Array (3/6)
//get student mark
System.out.print(“Mark 6:”);
mark6 = input.nextInt();
System.out.print(“Mark 7:”);
mark7 = input.nextInt();
System.out.print(“Mark 8:”);
mark8 = input.nextInt();
System.out.print(“Mark 9:”);
mark9 = input.nextInt();
System.out.print(“Mark 10:”);
mark10 = input.nextInt();

What would happen if there were 1000 students?


5 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Solution Without Array (4/6)
//calculate total marks
totalMarks = mark1 + mark2 + mark3 + mark4
+ mark5 + mark6 + mark7 + mark8 + mark9
+ mark10;

//calculate average mark


markAverage = totalMark/10;

What would happen if there were 1000 students?


6 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Solution Without Array (5/6)
//calculate number of student above average
if (mark1 > markAverage) studentNumber++;
if (mark2 > markAverage) studentNumber++;
if (mark3 > markAverage) studentNumber++;
if (mark4 > markAverage) studentNumber++;
if (mark5 > markAverage) studentNumber++;
if (mark6 > markAverage) studentNumber++;
if (mark7 > markAverage) studentNumber++;
if (mark8 > markAverage) studentNumber++;
if (mark9 > markAverage) studentNumber++;
if (mark10 > markAverage) studentNumber++;

What would happen if there were 1000 students?


7 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Solution Without Array (6/6)
//print the result

System.out.println(“number of student that


get more than average = “ +
studentNumber);
}
}

8 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Array (Definitions)
 Instead of using 10 variables to represent 10 student
marks,another technique is using one-dimensional
array for storing a list of marks.
 Array is a collection of memory location that is used
for storing data with the same type. Each memory
location in array is referred by array’s name and
location memory index.

9 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Array VS Normal Variables
mark
 Normal Variable
int mark;
mark
mark[0]
mark[1]
 Array Variable mark[2]
int[] mark = new int[10]; mark[3]
mark[4]
mark[5]
mark[6]
mark[7]
mark[8]
mark[9]
10 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Indices (Subscript)(1/2)
mark  Single element in array
is retrieved using index
[0] 67
 Indices start from 0;
A [1] 76
r
the 1st element of an
[2] 34 array mark is referred to
r
a [3] 47 as mark[0] and the n-th
y [4] 54 element as mark[n-1].
[5] 82
I  An index can have any
n [6] 38 int value from 0 to
d [7] 63 array’s length - 1.
e
[8] 72
x
[9] 24
11 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Indices (Subscript)(2/2)
 An index is written within square
mark brackets after array’s name

[0] 67  To retrieve 1st element in array


[1] 76 element1=mark[0];
[2] 34
Array Index
[3] 47
 To retrieve 6th element in array.
[4] 54 element6=mark[5];
[5] 82
[6] 38 Array Index
[7] 63  To retrieve nth element in array

[8] 72 elementn=mark[n-1];
[9] 24
12 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Declare One Dimensional Array (1/3)

 Syntax 1
DataType [ ] variableName = new DataType[arraysize
of type integer]

 Example :
define an array variable called monthName of
type String with length 12

String[ ] monthName = new String[12];

13 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Declare One Dimensional Array (2/3)

 Syntax 2
DataType [ ] variableName;
variableName = new DataType[arraySize of type integer]

 Example :
define an array variable called studentNum of type integer
with length indicate by user input;

int length;
int[ ] studentNum;
length = input.nextInt();
studentNum = new int[length];

14 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Declare One Dimensional Array (3/3)
n items
 Syntax 3
DataType [ ] variableName = {value1, value2. value3….};

where n items automatically defined as an array length

 Example :
define an array variable called keyCode of type integer that
contains 1,6,7,3,4,2,1 as it values;

int[ ] keyCode ={1,6,7,3,4,2,1}

What is the length/size of array keyCode?


15 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Instance Variable length

 For each array that has been instantiated, there


is a variable called length
 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.
<arrayName>.length

16 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


length Example
EXAMPLE 1:

int[ ] mark = new int[4];


mark.length 4
System.out.println(“the size of mark’s array is”+ mark.length);

OUTPUT:
the size of mark’s array is 4
snakeLocation.length 10
EXAMPLE 2: 1 2 3 4 5 6 7 8 9 10
int[ ] snakeLocation = {10,23,34,49,66,83,86,90,95,99};
System.out.println(“the size of array snakeLocation is”+ snakeLocation.length);

OUTPUT:
the size of snakeLocation’s array is 10

17 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Processing One Dimensional Array

 Using loops to step through elements in array and


perform the operations.
declarations
int [] list = new int [100];
int i;

Using for loop to assign an input into the array


for (i=0;i< list.length;i++)
list[i] = input.nextInt();

Using for loop to display all elements in array


for (i = 0; i < list.length; i++)
for (i=0;i< list.length;i++)
System.out.print(list[i] + " ");
System.out.println(list[i] + “ “);

18 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Common Operation on Array (1)
Initialize an array to a specific value

double[] sales = new double[4];


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

sales[2]=16.0;

19 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Common Operation on Array (1)
Initialize an array to a specific value
double[] sales = new double[4];

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


sales[index] = 10.0; sales[2]=10.0
sales[3]=10.0
sales[0]=10.0
sales[1]=10.0

sales[2]=16.0;

index sales.length
14320 4 false
true
sales

[0] 10.0
?
[1] 10.0
?
[2] 16.0
10.0
?
[3] 10.0
?

20 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Common Operation on Array (2)
Read data into an array

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


System.out.print(“Total Sales for Month “+(index+1)+ “:”);
sales[index] = input.nextDouble();
}

21 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Common Operation on Array (2)
Read data into an array
014
2
3 < 4 truefalse
for (index = 0; index < sales.length; index++){
System.out.print(“Total Sales for Month “+(index+1)+ “:”);
sales[index] = input.nextDouble();
}

Total Sales for Month 1 : 15.7


sales Total Sales for Month 2 : 19.7
Total Sales for Month 3 : 0.57
Total Sales for Month 4 : 13.0
0 10.0
15.7
1 19.7
10.0
2 0.57
16.0
3 10.0
13.0
22 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Common Operation on Array (3)
Print the contains of the array
System.out.println(“Month” + “ “ + “ Total Sales”);

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


System.out.println((index+1) + “ “ +sales[index]");

Month Total Sales


sales 1 15.7
2 19.7
3 0.57
0 15.7 4 13.0
1 19.7
2 0.57
3 13.0
23 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Common Operation on Array (3)
Print the contains of the array
System.out.println(“Month” + “ “ + “ Total Sales”);
43120 < 4 true
false
for (index = 0; index < sales.length; index++)
System.out.println((index+1) + “ “ +sales[index]");

Month Total Sales


sales 1 15.7
2 19.7
3 0.57
0 15.7 4 13.0
1 19.7
2 0.57
3 13.0
24 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Common Operation on Array (4)
Find sum and average of array
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;
sales sum average

48.97
35.4
15.7
35.97
0 12.2425
0 15.7
1 19.7
2 0.57

25 3 13.0
TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Common Operation on Array (4)
Find sum and average of array
sum = 0;
43210 < 4 true
false
for (index = 0; index < sales.length; index++)
sum = sum + sales[index];

if (sales.length != 0) true
average = sum / sales.length; 48.97/4
else
average = 0.0;
sales sum average

48.97
35.4
15.7
35.97
0 12.2425
0 15.7
1 19.7
2 0.57

26 3 13.0
TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Common Operation on Array (5)
Determining largest element in array

maxIndex = 0;

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

if (sales[maxIndex] < sales[index])


maxIndex = index;
largestSale = sales[maxIndex];
sales
largeSale 19.7
0 15.7
1 19.7
2 0.57

27 3 13.0
TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Common Operation on Array (5)
Determining largest element in array

maxIndex = 0; maxIndex 10

4213 < 4 false


true
for (index = 1; index < sales.length; index++)
15.7
19.7 < 19.7
13.0
0.57 true
false
if (sales[maxIndex] < sales[index])
maxIndex = index;
largestSale = sales[maxIndex];
sales
largeSale 19.7
0 15.7
1 19.7
2 0.57

28 3 13.0
TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Common Operation on Array (6)
Copying Arrays

The System.arraycopy() method

//original array
int ori[] = {1,2,3,4,5,,6};

//destination array
int dest[] = {10,9,8,7,6,5,4,3,2,1};

//copy all of the ori array to the dest array,


//starting with index 0
System.arraycopy(ori,0,dest,0,ori.length);

//result
dest has the following contents 1,2,3,4,5,6,4,3,2,1

29 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Array Index Out of Bounds(1/2)

 An array is in bounds if:


0 <= index <= arraySize – 1

 If index < 0 or index > arraySize:


ArrayIndexOutOfBoundsException exception is
thrown

30 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Array Index Out of Bounds(2/2)

31 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


RelationalOperator
Relational Operators Arrays
and Array (1/2)

int[] listA = new int[3];


int[] listB = new int[3];

if (listA == listB)
...

 The expression listA == listB determines if the values


of listA and listB are the same, thus determining
whether listA and listB refer to the same array.

 To determine whether listA and listB contain the same


elements, you need to compare them element by element.

32 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


RelationalOperator
Relational Operators Arrays
and Array (2/2)

int[] listA = new int[4];


int[] listB = new int[3];

if (listA == listB) false

listB = listA;

if (listA == listB) true


listA listB

0 15.7 0 15.7
1 19.7 1 19.7
2 0.57 2 0.57

33 3 13.0
TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007
Multi Dimensional Array

Arrray of arrays
int twoDim[] = new int [4][];
twoDim[0] = new int[2];
twoDim[1] = new int[2];
twoDim[2] = new int[3];

twoDim
0 34

2 1 19
twoDim[0] 0
1 19
twoDim[1]
0 23
twoDim[2]
1 19
twoDim[3]
2 0 twoDim[1][1]

34 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Relational
Example Operators
of Array UsageArrays
(1)

write a program that accept 10 student


marks, calculating mark average, and then
print out number of students that get
more than mark average.

35 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Example of Array Usage (1/7)
1. start
2. Get student mark
1. Repeat 3 times
1. Get student mark and store in array
3. Calculate total mark
1. While not end of array
1. Get element in the array
2. Add the element to the sum
4. Calculate average mark
1. Average = sum / size of array
5. Calculate number of student over average
1. While not end of array
1. Get element in array
2. Compare element with the average
1. If greater or equal than
1. Increase numberOf StudentoverAverage by 1
6. Display Result
7. End

36 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Example of Array Usage (2/7)
//1.start
import java.util.Scanner;
public class StudentOverAverage {
public static void main(String[] args) {

//declaration
int[] mark = new int[3];
int sum = 0;
int index ;
int average = 0;
int numberOfStudentOverAverage=0;
Scanner input = new Scanner (System.in);

37 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Example of Array Usage (3/7)

//2. Get student mark


// 1. Repeat 3 times
// 1.Get student mark and store in array

for (index=0;index < mark.length;index++){


System.out.println(“Enter Marks “ + (index+1));
mark[index] = input.getInt();
}

38 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Example of Array Usage (4/7)

//3. Calculate total mark


// 1.While not end of array
// 1.Get element in the array
// 1.Add the element to the sum

for (index=0;index < mark.length;index++){


sum = sum + mark[index]
}

39 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Example of Array Usage (5/7)

//4.Calculate average mark


// 1. Average = sum / size of array

average = sum / mark.length;

40 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Example of Array Usage (6/7)

//5. Calculate number of student over average


// 1. While not end of array
// 1. Get element in array
// 1. Compare element with the average
// 2. If greater or equal than
// 1.Increase
// numberOfStudentoverAverage by 1

for (index=0;index < mark.length;index++){


if (mark[index] >= average)
numberOfStudentOverAverage++;
}

41 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Example of Array Usage (7/7)

//6. Display Result


System.out.println(“Number of student over
avegare are: “ + numberOfStudentOverAverage );

//7. end
}
}

42 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007


Case Study

100 students were asked to rate the


quality of the food in the student
cafeteria on a scale of 1 to 10 (1 means
awful and 10 means excellent). Based on
the response,
1. summarize the result of the poll.
eq:
Rank Frequency Histogram
1 12 ************
2 5 *****
2. Calculate the Min, mode and median.
43 TMK3102 – PENGATURCARAAN KOMPUTER JUL 2006/2007

Вам также может понравиться