SlideShare a Scribd company logo
1
Chapter 3 Arrays : Motivations
Often you will have to store a large number of values during
the execution of a program. Suppose, for instance, that you
need to read one hundred numbers, compute their average, and
find out how many numbers are above the average. Your
program first reads the numbers and computes their average,
and then compares each number with the average to determine
whether it is above the average. The numbers must all be stored
in variables in order to accomplish this task. You have to
declare one hundred variables and repeatedly write almost
identical code one hundred times. From the standpoint of
practicality, it is impossible to write a program this way. So,
how do you solve this problem?
2
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
double[] myList = new double[10];
myList reference
myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Element value
Array reference
variable
Array element at
index 5
3
Declaring Array Variables
datatype[] arrayRefVar;
Example:
double[] myList;
datatype arrayRefVar[];
// This style is allowed, but not preferred
Example:
double myList[];
4
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
5
Declaring and Creating
in One Step
datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];
datatype arrayRefVar[] = new
datatype[arraySize];
double myList[] = new double[10];
6
The Length of an Array
Once an array is created, its size is fixed. It cannot be
changed. You can find its size using
arrayRefVar.length
For example,
myList.length returns 10
7
Indexed Variables
The array elements are accessed through the index. The
array indices are 0-based, i.e., it starts from 0 to
arrayRefVar.length-1. In the example in Figure 3.1,
myList holds ten double values and the indices are
from 0 to 9.
Each element in the array is represented using the
following syntax, known as an indexed variable:
arrayRefVar[index];
8
Using Indexed Variables
After an array is created, an indexed variable can
be used in the same way as a regular variable.
For example, the following code adds the value
in myList[0] and myList[1] to myList[2].
myList[2] = myList[0] + myList[1];
9
Array Initializers
Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one
statement.
10
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the
following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
11
CAUTION
Using the shorthand notation, you
have to declare, create, and initialize
the array all in one statement.
Splitting it would cause a syntax
error. For example, the following is
wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
12
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
Declare array variable values, create an
array, and assign its reference to values
After the array is created
0
1
2
3
4
0
0
0
0
0
animation
13
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] =i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i becomes 1
After the array is created
0
1
2
3
4
0
0
0
0
0
animation
14
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (=1) is less than 5
After the array is created
0
1
2
3
4
0
0
0
0
0
animation
15
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line is executed, value[1] is 1
After the first iteration
0
1
2
3
4
0
1
0
0
0
animation
16
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After i++, i becomes 2
animation
After the first iteration
0
1
2
3
4
0
1
0
0
0
17
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i+ values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (= 2) is less than 5
animation
After the first iteration
0
1
2
3
4
0
1
0
0
0
18
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line is executed,
values[2] is 3 (2 + 1)
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
19
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this, i becomes 3.
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
20
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (=3) is still less than 5.
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
21
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line, values[3] becomes 6 (3 + 3)
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
22
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this, i becomes 4
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
23
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (=4) is still less than 5
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
24
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this, values[4] becomes 10 (4 + 6)
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
animation
25
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After i++, i becomes 5
animation
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
26
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i ( =5) < 5 is false. Exit the loop
animation
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
27
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line, values[0] is 11 (1 + 10)
0
1
2
3
4
11
1
3
6
10
animation
28
Example: Analyzing Array Elements
Objective:
The program receives 6 numbers from the user,
Finds the largest number
And counts the occurrence of the largest number
entered.
Suppose you entered 3, 5, 2, 5, 5, and 5,
the largest number is 5
and its occurrence count is 4. TestArrayTestArray
29
Problem: Assigning Grades
Objective: read student scores (int), get the best
score, and then assign grades based on the
following scheme:
– Grade is A if score is >= best–10;
– Grade is B if score is >= best–20;
– Grade is C if score is >= best–30;
– Grade is D if score is >= best–40;
– Grade is F otherwise.
AssignGradeAssignGrade
30
Two-dimensional Arrays
Chicago
Boston
New York
Atlanta
Miami
Dallas
Houston
Distance Table (in miles)
Chicago Boston New York Atlanta Miami Dallas Houston
0 983 787 714 1375 967 1087
983 0 214 1102 1763 1723 1842
787 214 0 888 1549 1548 1627
714 1102 888 0 661 781 810
1375 1763 1549 661 0 1426 1187
967 1723 1548 781 1426 0 239
1087 1842 1627 810 1187 239 0
1723 1548 781 1426 0 239
Thus far, you have used one-dimensional arrays to model linear
collections of elements. You can use a two-dimensional array to
represent a matrix or a table. For example, the following table that
describes the distances between the cities can be represented using
a two-dimensional array.
31
Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;
// Create array and assign its reference to variable
refVar = new dataType[10][10];
// Combine declaration and creation in one statement
dataType[][] refVar = new dataType[10][10];
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
32
Declaring Variables of Two-
dimensional Arrays and Creating
Two-dimensional Arrays
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);
double[][] x;
33
Two-dimensional Array Illustration
0 1 2 3 4
0
7
0 1 2 3 4
1
2
3
4
0
1
2
3
4
matrix[2][1] = 7;matrix = new int[5][5];
3
7
0 1 2
0
1
2
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
1 2 3
4 5 6
8 9
10 11 12
array.length? 4
array[0].length? 3
matrix.length? 5
matrix[0].length? 5
34
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use an array initializer to declare, create and
initialize a two-dimensional array. For example,
int[][] array = new int[4][3];
array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
Same as
35
Lengths of Two-dimensional
Arrays
x
x[0]
x[1]
x[2]
x[0][0] x[0][1] x[0][2] x[0][3]
x[1][0] x[1][1] x[1][2] x[1][3]
x[2][0] x[2][1] x[2][2] x[2][3]
x.length is 3
x[0].length is 4
x[1].length is 4
x[2].length is 4
int[][] x = new int[3][4];
36
Lengths of Two-dimensional
Arrays, cont.
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
array.length
array[0].length
array[1].length
array[2].length
array[3].length
array[4].length ArrayIndexOutOfBoundsException
37
Ragged Arrays
Each row in a two-dimensional array is itself an array. So,
the rows can have different lengths. Such an array is
known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
matrix.length is 5
matrix[0].length is 5
matrix[1].length is 4
matrix[2].length is 3
matrix[3].length is 2
matrix[4].length is 1
38
Ragged Arrays, cont.
1 2 3 4 5int[][] triangleArray = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
1 2 3 4
1 2 3
1 2
1 2
39
Problem: Grading Multiple-
Choice Test
Objective: write a
program that grades
multiple-choice test.A B A C C D E E A D
D B A B C A E E A D
E D D A C B E E A D
C B A E D C E E A D
A B D C C D E E A D
B B E C C D E E A D
B B A C C D E E A D
E B E C C D E E A D
0 1 2 3 4 5 6 7 8 9
Student 0
Student 1
Student 2
Student 3
Student 4
Student 5
Student 6
Student 7
Students’ Answers to the Questions:
D B D C C D A E A D
0 1 2 3 4 5 6 7 8 9
Key
Key to the Questions:
GradeExamGradeExam
40
Problem: Finding Two Points
Nearest to Each Other
FindNearestPointsFindNearestPoints
(1, 1)
(-1, -1)
(-1, 3)
(2, 0.5)
(3, 3)
(4, 2)
(2, -1)
(4, -0.5)
-1 3
-1 -1
1 1
2 0.5
2 -1
3 3
4 2
4 -0.5
x y
0
1
2
3
4
5
6
7
41
Case Study: Sudoku
5 3 7
6 1 9 5
9 8 6
8 6 3
4 8 3 1
7 2 6
6
4 1 9 5
8 7 9
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
The objective is to fill the grid (see Figure 3.2(a)) so that every row,
every column, and every 3×3 box contain the numbers 1 to 9, as
shown in Figure 3.2(b).
42
Case Study: Sudoku
SudokuSudoku
int[][] grid =
{{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
int[][] freeCellList =
{{0, 2}, {0, 3}, {0, 5}, {0, 6}, {0, 7}, {0, 8},
{1, 1}, {1, 2}, {1, 6}, {1, 7}, {1, 8},
{2, 0}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {2, 8},
{3, 1}, {3, 2}, {3, 3}, {3, 5}, {3, 6}, {3, 7},
{4, 1}, {4, 2}, {4, 4}, {4, 6}, {4, 7},
{5, 1}, {5, 2}, {5, 3}, {5, 5}, {5, 6}, {5, 7},
{6, 0}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 8},
{7, 0}, {7, 1}, {7, 2}, {7, 6}, {7, 7},
{8, 0}, {8, 1}, {8, 2}, {8, 3}, {8, 5}, {8, 6}
};

More Related Content

What's hot (20)

PPT
Java™ (OOP) - Chapter 5: "Methods"
Gouda Mando
 
PPTX
07. Java Array, Set and Maps
Intro C# Book
 
PPTX
16. Arrays Lists Stacks Queues
Intro C# Book
 
PPTX
07. Arrays
Intro C# Book
 
PPTX
18. Java associative arrays
Intro C# Book
 
PPTX
02. Data Types and variables
Intro C# Book
 
PPTX
19. Data Structures and Algorithm Complexity
Intro C# Book
 
PPT
06slide
Dorothea Chaffin
 
PDF
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
PPTX
20.1 Java working with abstraction
Intro C# Book
 
PPTX
15. Streams Files and Directories
Intro C# Book
 
PDF
INTRODUCTION TO MATLAB session with notes
Infinity Tech Solutions
 
PPTX
10. Recursion
Intro C# Book
 
PPTX
09. Java Methods
Intro C# Book
 
PDF
Computer java programs
ADITYA BHARTI
 
PPTX
Java Foundations: Objects and Classes
Svetlin Nakov
 
PPT
13slide graphics
Dorothea Chaffin
 
PPTX
20.3 Java encapsulation
Intro C# Book
 
PPTX
DSA 103 Object Oriented Programming :: Week 5
Ferdin Joe John Joseph PhD
 
PPTX
13 Strings and Text Processing
Intro C# Book
 
Java™ (OOP) - Chapter 5: "Methods"
Gouda Mando
 
07. Java Array, Set and Maps
Intro C# Book
 
16. Arrays Lists Stacks Queues
Intro C# Book
 
07. Arrays
Intro C# Book
 
18. Java associative arrays
Intro C# Book
 
02. Data Types and variables
Intro C# Book
 
19. Data Structures and Algorithm Complexity
Intro C# Book
 
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
20.1 Java working with abstraction
Intro C# Book
 
15. Streams Files and Directories
Intro C# Book
 
INTRODUCTION TO MATLAB session with notes
Infinity Tech Solutions
 
10. Recursion
Intro C# Book
 
09. Java Methods
Intro C# Book
 
Computer java programs
ADITYA BHARTI
 
Java Foundations: Objects and Classes
Svetlin Nakov
 
13slide graphics
Dorothea Chaffin
 
20.3 Java encapsulation
Intro C# Book
 
DSA 103 Object Oriented Programming :: Week 5
Ferdin Joe John Joseph PhD
 
13 Strings and Text Processing
Intro C# Book
 

Viewers also liked (9)

PPTX
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
Khirulnizam Abd Rahman
 
PPTX
Android app development hybrid approach for beginners - Tools Installations ...
Khirulnizam Abd Rahman
 
PPTX
Android app development Hybrid approach for beginners
Khirulnizam Abd Rahman
 
PPTX
Mobile Web App development multiplatform using phonegap-cordova
Khirulnizam Abd Rahman
 
PPT
Chapter 6 Java IO File
Khirulnizam Abd Rahman
 
PPTX
Topik 3 Masyarakat Malaysia dan ICT
Khirulnizam Abd Rahman
 
PPTX
Tips menyediakan slaid pembentangan berkesan - tiada template
Khirulnizam Abd Rahman
 
PPT
Chapter 5 Class File
Khirulnizam Abd Rahman
 
PPTX
Html5 + Bootstrap & Mobirise
Khirulnizam Abd Rahman
 
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
Khirulnizam Abd Rahman
 
Android app development hybrid approach for beginners - Tools Installations ...
Khirulnizam Abd Rahman
 
Android app development Hybrid approach for beginners
Khirulnizam Abd Rahman
 
Mobile Web App development multiplatform using phonegap-cordova
Khirulnizam Abd Rahman
 
Chapter 6 Java IO File
Khirulnizam Abd Rahman
 
Topik 3 Masyarakat Malaysia dan ICT
Khirulnizam Abd Rahman
 
Tips menyediakan slaid pembentangan berkesan - tiada template
Khirulnizam Abd Rahman
 
Chapter 5 Class File
Khirulnizam Abd Rahman
 
Html5 + Bootstrap & Mobirise
Khirulnizam Abd Rahman
 
Ad

Similar to Chapter 3 Arrays in Java (20)

PPTX
Arrays and Detailed explanation of Array
Dr. Jasmine Beulah Gnanadurai
 
PPT
Capitulo 1 de java array unidimensionales
DiegoGamboaSafla
 
PPT
Java™ (OOP) - Chapter 6: "Arrays"
Gouda Mando
 
PPT
07slide.ppt
ankurgupta857016
 
PPTX
Data Structures and Algorithoms 07slide - 1D Arrays.pptx
AliciaLee77
 
PDF
Lecture06 computer applicationsie1_dratifshahzad
Atif Shahzad
 
PDF
Array
Scott Donald
 
PPTX
07+08slide.pptx
MURADSANJOUM
 
PPT
Lecture 8
Soran University
 
PDF
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
 
PPTX
Arrays in programming
TaseerRao
 
PPT
ch06.ppt
AqeelAbbas94
 
PPT
ch06.ppt
ansariparveen06
 
PPT
array Details
shivas379526
 
PPT
ch06.ppt
chandrasekar529044
 
PPT
Multi dimensional arrays
Aseelhalees
 
PPT
Array
PRN USM
 
PPT
Java căn bản - Chapter10
Vince Vo
 
PPT
05slide_arrays_creation_searching_sorting.ppt
ramesh504657
 
PDF
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
Arrays and Detailed explanation of Array
Dr. Jasmine Beulah Gnanadurai
 
Capitulo 1 de java array unidimensionales
DiegoGamboaSafla
 
Java™ (OOP) - Chapter 6: "Arrays"
Gouda Mando
 
07slide.ppt
ankurgupta857016
 
Data Structures and Algorithoms 07slide - 1D Arrays.pptx
AliciaLee77
 
Lecture06 computer applicationsie1_dratifshahzad
Atif Shahzad
 
07+08slide.pptx
MURADSANJOUM
 
Lecture 8
Soran University
 
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
 
Arrays in programming
TaseerRao
 
ch06.ppt
AqeelAbbas94
 
ch06.ppt
ansariparveen06
 
array Details
shivas379526
 
Multi dimensional arrays
Aseelhalees
 
Array
PRN USM
 
Java căn bản - Chapter10
Vince Vo
 
05slide_arrays_creation_searching_sorting.ppt
ramesh504657
 
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
Ad

More from Khirulnizam Abd Rahman (18)

PPTX
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Khirulnizam Abd Rahman
 
DOCX
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Khirulnizam Abd Rahman
 
PPTX
Topik 1 Islam dan Teknologi Maklumat
Khirulnizam Abd Rahman
 
PDF
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Khirulnizam Abd Rahman
 
PPT
Chapter 1 Nested Control Structures
Khirulnizam Abd Rahman
 
PPT
Chapter 1 nested control structures
Khirulnizam Abd Rahman
 
PDF
DTCP2023 Fundamentals of Programming
Khirulnizam Abd Rahman
 
PDF
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Khirulnizam Abd Rahman
 
PPTX
Simple skeleton of a review paper
Khirulnizam Abd Rahman
 
PDF
Airs2014 brochure
Khirulnizam Abd Rahman
 
DOCX
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
Khirulnizam Abd Rahman
 
PPTX
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam Abd Rahman
 
DOCX
Maklumat program al quran dan borang
Khirulnizam Abd Rahman
 
PDF
Senarai doa al-mathurat sughro - dengan terjemahan
Khirulnizam Abd Rahman
 
PDF
Al mathurat sughra - ringkas - m-mathurat
Khirulnizam Abd Rahman
 
PPT
Kemalangan akibat tumpuan terganggu
Khirulnizam Abd Rahman
 
PPTX
Android development beginners faq
Khirulnizam Abd Rahman
 
PPT
Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam Abd Rahman
 
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Khirulnizam Abd Rahman
 
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Khirulnizam Abd Rahman
 
Topik 1 Islam dan Teknologi Maklumat
Khirulnizam Abd Rahman
 
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Khirulnizam Abd Rahman
 
Chapter 1 Nested Control Structures
Khirulnizam Abd Rahman
 
Chapter 1 nested control structures
Khirulnizam Abd Rahman
 
DTCP2023 Fundamentals of Programming
Khirulnizam Abd Rahman
 
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Khirulnizam Abd Rahman
 
Simple skeleton of a review paper
Khirulnizam Abd Rahman
 
Airs2014 brochure
Khirulnizam Abd Rahman
 
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
Khirulnizam Abd Rahman
 
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam Abd Rahman
 
Maklumat program al quran dan borang
Khirulnizam Abd Rahman
 
Senarai doa al-mathurat sughro - dengan terjemahan
Khirulnizam Abd Rahman
 
Al mathurat sughra - ringkas - m-mathurat
Khirulnizam Abd Rahman
 
Kemalangan akibat tumpuan terganggu
Khirulnizam Abd Rahman
 
Android development beginners faq
Khirulnizam Abd Rahman
 
Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam Abd Rahman
 

Recently uploaded (20)

PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Digital Circuits, important subject in CS
contactparinay1
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 

Chapter 3 Arrays in Java

  • 1. 1 Chapter 3 Arrays : Motivations Often you will have to store a large number of values during the execution of a program. Suppose, for instance, that you need to read one hundred numbers, compute their average, and find out how many numbers are above the average. Your program first reads the numbers and computes their average, and then compares each number with the average to determine whether it is above the average. The numbers must all be stored in variables in order to accomplish this task. You have to declare one hundred variables and repeatedly write almost identical code one hundred times. From the standpoint of practicality, it is impossible to write a program this way. So, how do you solve this problem?
  • 2. 2 Introducing Arrays Array is a data structure that represents a collection of the same types of data. 5.6 4.5 3.3 13.2 4 34.33 34 45.45 99.993 11123 double[] myList = new double[10]; myList reference myList[0] myList[1] myList[2] myList[3] myList[4] myList[5] myList[6] myList[7] myList[8] myList[9] Element value Array reference variable Array element at index 5
  • 3. 3 Declaring Array Variables datatype[] arrayRefVar; Example: double[] myList; datatype arrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];
  • 4. 4 Creating Arrays arrayRefVar = new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.
  • 5. 5 Declaring and Creating in One Step datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10]; datatype arrayRefVar[] = new datatype[arraySize]; double myList[] = new double[10];
  • 6. 6 The Length of an Array Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayRefVar.length For example, myList.length returns 10
  • 7. 7 Indexed Variables The array elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. In the example in Figure 3.1, myList holds ten double values and the indices are from 0 to 9. Each element in the array is represented using the following syntax, known as an indexed variable: arrayRefVar[index];
  • 8. 8 Using Indexed Variables After an array is created, an indexed variable can be used in the same way as a regular variable. For example, the following code adds the value in myList[0] and myList[1] to myList[2]. myList[2] = myList[0] + myList[1];
  • 9. 9 Array Initializers Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.
  • 10. 10 Declaring, creating, initializing Using the Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
  • 11. 11 CAUTION Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double[] myList; myList = {1.9, 2.9, 3.4, 3.5};
  • 12. 12 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } Declare array variable values, create an array, and assign its reference to values After the array is created 0 1 2 3 4 0 0 0 0 0 animation
  • 13. 13 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] =i + values[i-1]; } values[0] = values[1] + values[4]; } } i becomes 1 After the array is created 0 1 2 3 4 0 0 0 0 0 animation
  • 14. 14 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (=1) is less than 5 After the array is created 0 1 2 3 4 0 0 0 0 0 animation
  • 15. 15 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line is executed, value[1] is 1 After the first iteration 0 1 2 3 4 0 1 0 0 0 animation
  • 16. 16 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After i++, i becomes 2 animation After the first iteration 0 1 2 3 4 0 1 0 0 0
  • 17. 17 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i+ values[i-1]; } values[0] = values[1] + values[4]; } } i (= 2) is less than 5 animation After the first iteration 0 1 2 3 4 0 1 0 0 0
  • 18. 18 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line is executed, values[2] is 3 (2 + 1) After the second iteration 0 1 2 3 4 0 1 3 0 0 animation
  • 19. 19 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, i becomes 3. After the second iteration 0 1 2 3 4 0 1 3 0 0 animation
  • 20. 20 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (=3) is still less than 5. After the second iteration 0 1 2 3 4 0 1 3 0 0 animation
  • 21. 21 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line, values[3] becomes 6 (3 + 3) After the third iteration 0 1 2 3 4 0 1 3 6 0 animation
  • 22. 22 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, i becomes 4 After the third iteration 0 1 2 3 4 0 1 3 6 0 animation
  • 23. 23 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (=4) is still less than 5 After the third iteration 0 1 2 3 4 0 1 3 6 0 animation
  • 24. 24 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, values[4] becomes 10 (4 + 6) After the fourth iteration 0 1 2 3 4 0 1 3 6 10 animation
  • 25. 25 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After i++, i becomes 5 animation After the fourth iteration 0 1 2 3 4 0 1 3 6 10
  • 26. 26 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i ( =5) < 5 is false. Exit the loop animation After the fourth iteration 0 1 2 3 4 0 1 3 6 10
  • 27. 27 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line, values[0] is 11 (1 + 10) 0 1 2 3 4 11 1 3 6 10 animation
  • 28. 28 Example: Analyzing Array Elements Objective: The program receives 6 numbers from the user, Finds the largest number And counts the occurrence of the largest number entered. Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its occurrence count is 4. TestArrayTestArray
  • 29. 29 Problem: Assigning Grades Objective: read student scores (int), get the best score, and then assign grades based on the following scheme: – Grade is A if score is >= best–10; – Grade is B if score is >= best–20; – Grade is C if score is >= best–30; – Grade is D if score is >= best–40; – Grade is F otherwise. AssignGradeAssignGrade
  • 30. 30 Two-dimensional Arrays Chicago Boston New York Atlanta Miami Dallas Houston Distance Table (in miles) Chicago Boston New York Atlanta Miami Dallas Houston 0 983 787 714 1375 967 1087 983 0 214 1102 1763 1723 1842 787 214 0 888 1549 1548 1627 714 1102 888 0 661 781 810 1375 1763 1549 661 0 1426 1187 967 1723 1548 781 1426 0 239 1087 1842 1627 810 1187 239 0 1723 1548 781 1426 0 239 Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent a matrix or a table. For example, the following table that describes the distances between the cities can be represented using a two-dimensional array.
  • 31. 31 Declare/Create Two-dimensional Arrays // Declare array ref var dataType[][] refVar; // Create array and assign its reference to variable refVar = new dataType[10][10]; // Combine declaration and creation in one statement dataType[][] refVar = new dataType[10][10]; // Alternative syntax dataType refVar[][] = new dataType[10][10];
  • 32. 32 Declaring Variables of Two- dimensional Arrays and Creating Two-dimensional Arrays int[][] matrix = new int[10][10]; or int matrix[][] = new int[10][10]; matrix[0][0] = 3; for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) matrix[i][j] = (int)(Math.random() * 1000); double[][] x;
  • 33. 33 Two-dimensional Array Illustration 0 1 2 3 4 0 7 0 1 2 3 4 1 2 3 4 0 1 2 3 4 matrix[2][1] = 7;matrix = new int[5][5]; 3 7 0 1 2 0 1 2 int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; 1 2 3 4 5 6 8 9 10 11 12 array.length? 4 array[0].length? 3 matrix.length? 5 matrix[0].length? 5
  • 34. 34 Declaring, Creating, and Initializing Using Shorthand Notations You can also use an array initializer to declare, create and initialize a two-dimensional array. For example, int[][] array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12; int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; Same as
  • 35. 35 Lengths of Two-dimensional Arrays x x[0] x[1] x[2] x[0][0] x[0][1] x[0][2] x[0][3] x[1][0] x[1][1] x[1][2] x[1][3] x[2][0] x[2][1] x[2][2] x[2][3] x.length is 3 x[0].length is 4 x[1].length is 4 x[2].length is 4 int[][] x = new int[3][4];
  • 36. 36 Lengths of Two-dimensional Arrays, cont. int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; array.length array[0].length array[1].length array[2].length array[3].length array[4].length ArrayIndexOutOfBoundsException
  • 37. 37 Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] matrix = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; matrix.length is 5 matrix[0].length is 5 matrix[1].length is 4 matrix[2].length is 3 matrix[3].length is 2 matrix[4].length is 1
  • 38. 38 Ragged Arrays, cont. 1 2 3 4 5int[][] triangleArray = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; 1 2 3 4 1 2 3 1 2 1 2
  • 39. 39 Problem: Grading Multiple- Choice Test Objective: write a program that grades multiple-choice test.A B A C C D E E A D D B A B C A E E A D E D D A C B E E A D C B A E D C E E A D A B D C C D E E A D B B E C C D E E A D B B A C C D E E A D E B E C C D E E A D 0 1 2 3 4 5 6 7 8 9 Student 0 Student 1 Student 2 Student 3 Student 4 Student 5 Student 6 Student 7 Students’ Answers to the Questions: D B D C C D A E A D 0 1 2 3 4 5 6 7 8 9 Key Key to the Questions: GradeExamGradeExam
  • 40. 40 Problem: Finding Two Points Nearest to Each Other FindNearestPointsFindNearestPoints (1, 1) (-1, -1) (-1, 3) (2, 0.5) (3, 3) (4, 2) (2, -1) (4, -0.5) -1 3 -1 -1 1 1 2 0.5 2 -1 3 3 4 2 4 -0.5 x y 0 1 2 3 4 5 6 7
  • 41. 41 Case Study: Sudoku 5 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 4 1 9 5 8 7 9 5 3 4 6 7 8 9 1 2 6 7 2 1 9 5 3 4 8 1 9 8 3 4 2 5 6 7 8 5 9 7 6 1 4 2 3 4 2 6 8 5 3 7 9 1 7 1 3 9 2 4 8 5 6 9 6 1 5 3 7 2 8 4 2 8 7 4 1 9 6 3 5 3 4 5 2 8 6 1 7 9 The objective is to fill the grid (see Figure 3.2(a)) so that every row, every column, and every 3×3 box contain the numbers 1 to 9, as shown in Figure 3.2(b).
  • 42. 42 Case Study: Sudoku SudokuSudoku int[][] grid = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, {0, 6, 0, 0, 0, 0, 2, 8, 0}, {0, 0, 0, 4, 1, 9, 0, 0, 5}, {0, 0, 0, 0, 8, 0, 0, 7, 9} }; int[][] freeCellList = {{0, 2}, {0, 3}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, {1, 1}, {1, 2}, {1, 6}, {1, 7}, {1, 8}, {2, 0}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {2, 8}, {3, 1}, {3, 2}, {3, 3}, {3, 5}, {3, 6}, {3, 7}, {4, 1}, {4, 2}, {4, 4}, {4, 6}, {4, 7}, {5, 1}, {5, 2}, {5, 3}, {5, 5}, {5, 6}, {5, 7}, {6, 0}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 8}, {7, 0}, {7, 1}, {7, 2}, {7, 6}, {7, 7}, {8, 0}, {8, 1}, {8, 2}, {8, 3}, {8, 5}, {8, 6} };