Lesson 2
RECAP
1. int z [ ] [ ]={{67,78,89};
{87,88,90};
{70,89,90}};
The above declarations give Compilation
errors. Spot the errors.
2. Declare and initialize a Two-dimensional
array that has three rows and three
columns with values that are of string data
type.
Lesson Objective
To create a two-dimensional array to store,
retrieve, and perform basic operations.
CONNECTING
Processing data that is stored as a collection of One-
dimensional arrays can be inconvenient in certain
situations. Coding becomes easier when a single
data structure is used to hold all the information.
A Two-Dimensional array can be used to store the
Math, Computer science and Physics marks of 30
students in a class, instead of three one dimensional
arrays.
SUCCESS CRITERIA
At the end of this lesson, you should be able to
Understand the structure of a Two-dimensional array
Create a Two-dimensional array.
Retrieve and store values in a Two-dimensional Array.
Display the contents of a Two-dimensional array.
Perform basic operations using a Two-dimensional
array.
INTRODUCTION
A Two-dimensional array is an array of arrays.
The length of a 2D array is the number of rows it has.
The number of columns may vary from row to row.
The row index runs from 0 to length-1. As each row
of a 2D array can have a different number of cells, so
each row has its own length.
<Arrayname>.Iength – a variable that gives the
number of rows in a 2D array
<arrayname><row index>.length – a variable that
gives the number of cells or columns in each row of a
2D array.
Two dimensional arrays are accessed with 2 indices.
Like one dimensional arrays, array indices start
from 0. So, 0,0 refers to first row and first column,
0,1 refers to first row and second column, 1,0
refers to second row and first column and so on.
To print a value that is in the 2nd row and 1st
column, the command is:
System.out.println(A[1][0]);
To store a value in the 1st row 4th column:
A[0][3]=50;
The formula for calculating the total number
of elements in a two-dimensional array is as
follows:
No.of elements = no.of rows x no.of columns
The formula for calculating the total number
of bytes required by a two-dimensional array
is as follows:
Total bytes = no.of rows x no.of columns x
size of data type
Using a Nested loop is an ideal technique to
display the contents of a matrix
class twod {
public static void main() {
int n[ ][ ]={{1,2,3},{4,5,6}};
for(int i=0;i<n.length;i++) {
for(int j=0;j<n[i].length;j++) {
System.out.print(n[i][j]+" ");
}
System.out.println();
}
}
}
Test your Understanding