SlideShare uma empresa Scribd logo
1 de 42
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}
};

Mais conteúdo relacionado

Mais procurados

Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"Gouda Mando
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories Intro C# Book
 
INTRODUCTION TO MATLAB session with notes
  INTRODUCTION TO MATLAB   session with  notes  INTRODUCTION TO MATLAB   session with  notes
INTRODUCTION TO MATLAB session with notesInfinity Tech Solutions
 
Computer java programs
Computer java programsComputer java programs
Computer java programsADITYA BHARTI
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and ClassesSvetlin Nakov
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 

Mais procurados (20)

Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
06slide
06slide06slide
06slide
 
DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
INTRODUCTION TO MATLAB session with notes
  INTRODUCTION TO MATLAB   session with  notes  INTRODUCTION TO MATLAB   session with  notes
INTRODUCTION TO MATLAB session with notes
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
Computer java programs
Computer java programsComputer java programs
Computer java programs
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
13slide graphics
13slide graphics13slide graphics
13slide graphics
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
DSA 103 Object Oriented Programming :: Week 5
DSA 103 Object Oriented Programming :: Week 5DSA 103 Object Oriented Programming :: Week 5
DSA 103 Object Oriented Programming :: Week 5
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 

Destaque

Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan HeartwareTopik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan HeartwareKhirulnizam Abd Rahman
 
Android app development hybrid approach for beginners - Tools Installations ...
Android app development  hybrid approach for beginners - Tools Installations ...Android app development  hybrid approach for beginners - Tools Installations ...
Android app development hybrid approach for beginners - Tools Installations ...Khirulnizam Abd Rahman
 
Android app development Hybrid approach for beginners
Android app development  Hybrid approach for beginnersAndroid app development  Hybrid approach for beginners
Android app development Hybrid approach for beginnersKhirulnizam Abd Rahman
 
Mobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordovaMobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordovaKhirulnizam Abd Rahman
 
Tips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada templateTips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada templateKhirulnizam Abd Rahman
 

Destaque (9)

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

Semelhante a Chapter 3 Arrays in Java

Semelhante a Chapter 3 Arrays in Java (20)

07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
 
Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"
 
Arrays
ArraysArrays
Arrays
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
 
Array
ArrayArray
Array
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
 
Array
ArrayArray
Array
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Ansi c
Ansi cAnsi c
Ansi c
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 

Mais de Khirulnizam Abd Rahman

Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072Khirulnizam Abd Rahman
 
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan InsanPanduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan InsanKhirulnizam Abd Rahman
 
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...Khirulnizam Abd Rahman
 
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan InsanNpwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan InsanKhirulnizam Abd Rahman
 
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell   khirulnizamRangka kursus pembangunan aplikasi android kuiscell   khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell khirulnizamKhirulnizam Abd Rahman
 
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copyKhirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copyKhirulnizam Abd Rahman
 
Senarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahanSenarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahanKhirulnizam Abd Rahman
 
Al mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathuratAl mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathuratKhirulnizam Abd Rahman
 
Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...Khirulnizam Abd Rahman
 

Mais de Khirulnizam Abd Rahman (18)

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

Último

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Último (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

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