You are on page 1of 12

TWO

DIMENSIONAL
ARRAY
By Abbas Ghalib
Two-Dimensional Array
Defining a Two-Dimensional Array
◦ Syntax

datatype arrayname[rowsize][columnsize];
◦ Example
int my_array[3][4];
Initializing a Two-Dimensional Array
◦ A Two-Dimensional Array can be initialized in the declaration statement:
◦ 1st method:
int a[3][4] = {
{22,33,12,56}. // elements of first row
{98,27,36,42}, // elements of second row
{67,85,34,76} }; // elements of third row
◦ 2nd method:
int a[3][4] = { {22,33,12,56}. {98,27,36,42}, {67,85,34,76} };
first row second row third row

◦ 3rd method:
int a[3][4] = { 22,33,12,56. 98,27,36,42, 67,85,34,76 };
first row second row third row
Problem: 01

Write a C++ program that multiply each element of array by


2 that has 3 rows and 4 columns and display it in the form
of matrix. The array is initialized to data values from 1 to 12
with 3 rows and 4 columns.
Solution

2 4 6 8Idea…..
The output should be:

10 12 14 16
18 20 22 24
To display on computer screen.
Solution (Step – 1)

Firstly, I should initialize the


array with numbers from 1 to
12 in the declaration statement.
Solution (Step – 1)
◦ Coding:
The following code will define and initialize the array;

#include <iostream> // preprocessor directives


using namespace std;
int main() // declaration of main function
{ // beginning of main body
int a[3][4] = { // array definition and initialization
{1,2,3,4}, // elements of 1st row
{5,6,7,8}, // elements of 2nd row
{9,10,11,12} }; // elements of 3rd row
Solution (Step -2)

Now, I need to access each element in the array


row by row and multiply it by 2 and display it on
screen. I am accessing it row-wise outer loop
contains row number and inner loop contains
column number.
Solution (Step -2)
◦ Coding:
The following code will access the array row by row and multiply each element in a row by 2
and print on screen;

for(int row = 0; row < 3; row++) // outer loop i-e row number
{ // body of outer loop
cout << endl; // print a blank line
for(int col = 0; col < 4; col++) // inner loop i-e column number
cout << “\t” << a[row][col] * 2; // multiply each element by 2 and print
} // end of outer loop
} // end of main body
Explanation (Deep Dive)

__
2 __
4 __
6 8
__

Outer
Condition
Let’s
10
__ took
__
12 Loop
false,
14
__ Condition
asodeeper
we proceed
__
16 dive to
Row = 2310 Col = 3140321

Failed
18
__
nextso
20
__
program
iteration
22

into it
__ __
24
ends.
Problem: 02

Write a C++ program that prompts the user to enter 12


integers in a two-dimensional array that has 3 rows and 4
columns and finds the largest integer.

You might also like