CSC138 - CH2 (Part 1)
CSC138 - CH2 (Part 1)
CHAPTER 2:
TWO DIMENSIONAL ARRAY
(2D-ARRAY)
LEARNING OBJECTIVES
Upon completion, you should be able to:
o be able to declare a two-dimensional array.
o be able to perform fundamental operations
on a two-dimensional array.
REVIEW DEFINITION OF EACH TYPE
OF ARRAY
1-DIMENSIONAL
ARRAY An array in which the elements are arranged
in a list form.
2-DIMENSIONAL
ARRAY A collection of a fixed number of elements
(called components) arranged in rows
and columns.
TWO DIMENSIONAL ARRAY
o The arrays we have used so far are referred to as single or
one-dimensional arrays because they use a single group of
items that can classified in a single column.
o In some cases, you may want to divided the list in two or
more sections. For example, here is a list of numbers divided
in various columns:
Array (0,0) Array (0,1) Array (0,2) Array (0,3) Array (0,4)
Array (1,0) Array (1,1) Array (1,2) Array (1,3) Array (1,4)
Array (2,0) Array (2,1) Array (2,2) Array (2,3) Array (2,4)
Array (3,0) Array (3,1) Array (3,2) Array (3,3) Array (3,4)
[0] 3 5 10 4 5
[1] 2 7 9 8 6
[2] 1 0 3 4 7
[3] 2 4 5 7 9
DECLARATION 2D ARRAY
o Declaration syntax:
data_type arrayName[int Exp1][int Exp2];
intExp1 and intExp2 specify the number of rows and the number of
columns, respectively, in the array.
[1] [1] 4 5 6
[1]
[2] [2] 7 [2] 7 8 9
int board [4] [3] = { {2, 3, 1}, board [0] [1] [2]
[0] 2 3 1
{15, 25, 13},
[1]
{20, 4, 7},
[2]
{11,18,14} };
[3]
2D ARRAY INITIALIZATION
o Example 2D array initialization:
int square[3][3] = { {1, 2, 3},
{4, 5 , 6}, {7, 8, 9} };
Input
Sum
Average
Count
Searching
Sorting
1. INITIALIZATION
o Initializing a single row:
• To initialize row number 4 to 0.
row = 4;
for(col = 0; col < Number_of_Columns; col++)
matrix[row][col]=0;
} sumRow
array
4. SUM
o To sum of the elements in the row:
4. SUM
o To sum of the elements in the row:
array
sumCol
4. SUM
o To sum of the elements in the column:
4. SUM
o To sum of the elements in the column:
CHAPTER 2:
TO BE CONTINUED….