38
12/7/2016 1 CSC138: STRUCTURED PROGRAMMING MULTI/TWO DIMENSIONAL ARRAY (2D) CONTENTS 2D array declaration and initialization Accessing and printing array components 2D array operations 2D array string manipulation ( Sort, Search) Application of multi dimensional array (Example : matrix, game) 2D Array and function

CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

1

CSC138: STRUCTURED

PROGRAMMING

MULTI/TWO DIMENSIONAL ARRAY (2D)

CONTENTS

2D array declaration and initialization

Accessing and printing array components

2D array operations

2D array string manipulation ( Sort, Search)

Application of multi dimensional array (Example : matrix, game)

2D Array and function

Page 2: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

2

Revision

What is the output of the following C++ code?

double salary[5] = {25000, 36500, 85000, 62500, 97000};

double raise = 0.03;

cout << fixed << showpoint << setprecision(2);

for (int i = 0; i < 5; i++)

cout << (i+1) << “ “ << salary[i] << “ “ << salary[i] * raise << endl;

Definitions

ARRAY A collection of a fixed number of elements

(called components) of the same type.

1-DIMENSIONAL

ARRAY An array in which the elements are arranged

in a list form.

2-DIMENSIONAL

ARRAYA collection of a fixed number of elements

(called components) arranged in rows

and columns.

n-DIMENSIONAL

ARRAY A collection of a fixed number of elements

arranged in n dimensions (n>=1).

Page 3: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

3

Introduction

• Two-dimensional array: collection of a

fixed number of components (of the same

type) arranged in two dimensions

– Sometimes called matrices or tables

• Declaration syntax:

Introduction

rows columns

Index /subscript

element

Page 4: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

4

• 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.

• 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:

• Instead of having two lists that represent the same types of values,

you can declare a single array variable and divide its list of items in

two. A two-dimensional array is an array made of two lists of items

of the same data type.

Two-Dimensional array

Two-Dimensional array• A collection of a fixed number of components arranged in

rows and columns, wherein all components are of the

same type.

• Declaration syntax:

data_type arrayName[intExp1][intExp2];

intExp1 and intExp2 specify the number of rows and the number of columns,

respectively, in the array.

• Example: int mark[4][5];

mark

[0]

[1]

[2]

[3]

[0] [1] [2] [3] [4]

Page 5: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

5

Two-dimensional Arrays

// Declare array ref var

elementType arrayName[rowSize][columnSize];

int matrix[5][5];

Two-dimensional Array Illustration

[0] [1] [2] [3] [4]

[0]

7

[1]

[2]

[3]

[4]

matrix[2][1] = 7;

int matrix[5][5];

7

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

[0] [1] [2] [3] [4] [0] [1] [2] [3]

[0]

[1]

[2]

[3]

[4]

[0]

[1]

[2]

[3]

Page 6: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

6

CONTENTS

2D Array Declaration and

Initialization

Array Initialization

int array[4][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };

(a)

Equivalent

int array[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;

(b)

To initialize the entire matrix to 0:

You can also use an array initializer to declare, create and initialize a two-

dimensional array. For example,

Page 7: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

7

Accessing elements

Accessing Array Components

• Need a pair of indices: one for the row position and one

for the column position.

• The syntax:

arrayName[indexExp1][indexExp2]

• Example:

sales[5][3]=25.75;

stores 25.75 into row number 5 and column number

3(6th row,4th column) of the array sales.

• int i=5; int j=3;

sales[5][3] is equivalent to sales[i][j]=25.75;

Page 8: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

8

• To access an element of a 2D array, we

must specify the row and column index.

• Example:

square [1][2]

824

674

927

square

[0]

[1]

[2]

[0] [1] [2]

Accessing Array Components

• Like 1D arrays,2D arrays can be

initialized when they are declared.

int square[3][3] = {{1, 2, 3}, {4, 5 , 6}, {7, 8, 9}};

321

654

987

square

[0]

[1]

[2]

[0] [1] [2]

2D arrays initialization

Page 9: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

9

int square[3][3] = {{1, 2, 3}, {4, 5 , 6}, {7, 8, 9}};

321

654

987

square

[0]

[1]

[2]

[0] [1] [2]

int square[3][3] = {{1, 2, 3}, {4, 5 , 6}, {7, 8, 9}};

321

654

987

square

[0]

[1]

[2]

2D arrays initialization

CONTENTS

Accessing and printing array components

Page 10: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

10

Input values

Example:

Const int NUMBER_OF_ROWS=2Const int NUMBER_OF_COLUMNS=3

int matrix[NUMBER_OF_ROWS][NUMBER_OF_ROWS];

0 1 2

0

1

Row column cin

0 0 x

1 x

2 x

1 0 x

1 x

2 x

Enumeration Type.

• Creating your own simple data types,

known as Enumeration Type.

• To define a new simple data type, called

enumeration type, we need three things:

– A name for the data type

– A set of values for the data type

– A set of operations on the values

Page 11: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

11

Input values

• Enumeration type

Input values

• Enumeration typeenum car{proton,produa};

enum color {white,red};

int sales[2][2];

for(int i=proton; i<=produa;i++)

for(int x=white; x<=red;x++)

cin>>sales[i][x];

for(int i=proton; i<=produa;i++)

for(int x=white; x<=red;x++)

cout<<sales[i][x];

cout<<"\nsales[proton][red] "<<sales[proton][red];

Page 12: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

12

Input values

• Enumeration typeconst int ROWS = 6;

const int COLS = 5;

void main()

{

enum carType {proton, produa};

carType car; //declare variable car as carType

enum colorType {white, red};

colorType color; //declare variable color as colorType

for (car=proton; car<=produa; car=static_cast<carType>(car+1))

{

for (color=white; color<=red; color=static_cast<colorType>(color+1))

cin >> inStock[car][color] << "\t ";

}

}

Output values

0 1 2

0

1

Page 13: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

13

Processing Arrays

�Using for loops to access entire array

� Using for loops to access particular row @ column.� Row processing

int row=4;for (int col = 0; col < 3; col++){sum = sum + matrix[row][column]}

0 1 2

4

for (int row = 0; row < 2; row++){for (int col = 0; col < 3; col++)

//process}

0 1 2

0

1

CONTENTS

2D array operations

Page 14: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

14

2D arrays Operations

• A 2D array can be processed in 3 ways:

– Process the entire array.(Initializing and printing the array)

– Process a particular row of the array, called row

processing.(Find the largest element and sum of a row)

– Process a particular column of the array, called column

processing. (Find the largest element and sum of a column)

• Given the following declaration

cons int NUM_OF_ROWS=7;

cons int NUM_OF_COLUMNS=6;

int matrix[NUM_OF_ROWS][NUM_OF_COLUMNS];

int row,col,sum,largest,temp;

2D arrays Operations

matrix [0] [1] [2] [3] [4] [5]

[0]

[1]

[2]

[3]

[4]

[5]

[6]

Page 15: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

15

2D arrays Operations• To process row number 5 of matrix.

The components of row number 5 of matrix are:

matrix[5][0],matrix[5][1],matrix[5][2],matrix[5][3],

matrix[5][4],matrix[5][5]

The first index is fixed at 5.The second index is ranges from 0 to 5.

for(col=0; col<Number_of_Columns; col++)

process matrix[5][col];

• To process column number 2 of matrix.

The components of row number 5 of matrix are:

matrix[0][2],matrix[1][2],matrix[2][2],matrix[3][2],

matrix[4][2],matrix[5][2],matrix[6][2]

The second index is fixed at 2.The first index is ranges from 0 to 6.

for(row=0; row<Number_of_Rows; row++)

process matrix[row][2];

Initialization

Print

Input

Sum by row

Sum by column

Largest element in each row and column

Sorting an array of strings in alphabetical order

2D arrays Operations

Page 16: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

16

1.Initialization

a) To initialize row number 4 to 0.

row=4;

for(col=0; col<Number_of_Columns; col++)

matrix[row][col]=0;

b) To initialize the entire matrix to 0

for(row=0; row<Number_of_Rows; row++)

{

for(col=0; col<Number_of_Columns; col++)

matrix[row][col]=0;

}

Initializing Arrays with Random Values

The following loop initializes the array with random values between 0 and 99:

for (int row = 0; row < rowSize; row++)

{

for (int column = 0; column < columnSize;column++)

{

matrix[row][column] = rand() % 100;

}

}

Page 17: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

17

Initializing Arrays with Random Values#include<iostream.h>

#include<stdlib.h>

const rowSize=3;

const columnSize=2;

void main()

{

int matrix[3][2];

for (int row = 0; row < rowSize; row++)

{

for (int column = 0; column < columnSize;column++)

{

matrix[row][column] = rand() % 100;

cout<<matrix[row][column]<<endl;

}

}}

34

Initializing Arrays with Random Values

Output:

Page 18: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

18

2.Print

To print a two-dimensional array, you have to print each element in the array using a loop like the following:

for (int row = 0; row < rowSize; row++)

{

for (int column = 0; column < columnSize; column++)

{

cout << matrix[row][column] << " ";

}

cout << endl;

}

36

2.Print#include<iostream.h>

#include<stdlib.h>

const rowSize=3;

const columnSize=2;

void main()

{

int matrix[3][2]={{1,2},{3,4},{5,6}};

for (int row = 0; row < rowSize; row++)

{

for (int column = 0; column < columnSize; column++)

{

cout << matrix[row][column] << " ";

}

cout << endl;

}

}

Page 19: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

19

3.Input

a) To input data into row number 4(fifth row)

row=4;

for(col=0; col<Number_of_Columns; col++)

cin>>matrix[row][col];

a) To input data into each component of matrix

for(row=0; row<Number_of_Rows; row++)

{

for(col=0; col<Number_of_Columns; col++)

cin>>matrix[row][col];

}

4.Sum by row

a) To find the sum of row number 4 of matrix; that is, it adds the

components of row number 4.

sum=0;

row=4;

for(col=0; col<Number_of_Columns; col++)

sum=sum+ matrix[row][col];

b) To find the sum of each row separately.

for(row=0; row<Number_of_Rows; row++)

{

sum=0;

for(col=0; col<Number_of_Columns; col++)

sum=sum+ matrix[row][col];

cout<<“Sum of row”<<row +1<<“=“<<sum<<endl;

}

Page 20: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

20

5.Sum by column

To find the sum of each individual column.

for(col=0; col<Number_of_Columns; col++)

{

sum=0;

for(row=0; row<Number_of_Rows; row++)

sum=sum+ matrix[row][col];

cout<<“Sum of column”<<col +1<<“=“sum<<endl;

}

6.Largest element in each row and

column

a) To determine the largest element in row 4.

row=4;

largest=matrix[row][0];//assume the first element

//of the row is the largest

for(col=1; col<Number_of_Columns; col++)

if (largest < matrix[row][col])

largest = matrix[row][col]);

Page 21: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

21

6.Largest element in each row and

column

b) To determine the largest element in each row.

for(row=0; row<Number_of_Rows; row++)

{

largest=matrix[row][0];

for(col=1; col<Number_of_Columns; col++)

if (largest < matrix[row][col])

largest = matrix[row][col]);

cout<<“The largest element in row”<<row +1<<“=“<<

largest<<endl;

}

6.Largest element in each row and

column

c) To determine the largest element in each column.

for(col=0; col<Number_of_Columns; col++)

{

largest=matrix[0][col];

for(row=1; row<Number_of_Rows; col++)

if (largest < matrix[row][col])

largest = matrix[row][col]);

cout<<“The largest element in column”<<col

+1<<“=“<<largest<<endl;

}

Page 22: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

22

Array operation

�To find the sum of each individual row:

3 1 4

1 2 3

2 2 2

0

1

2

0 1 2

Sum of row 1 = 8

Sum of row 2 = 6

Sum of row 3 = 6

Array operation

�To find the sum of each individual column:

3 1 4

1 2 3

2 2 2

0

1

2

0 1 2

Sum of column 1 = 6

Sum of column 2 = 5

Sum of column 3 = 9

Page 23: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

23

Array operation

�Largest Element in Each Row and Each Column

3 1 4

1 2 3

2 2 2

0

1

2

0 1 2

Exercise #1

Consider the following declarations:

const int CAR_TYPES = 5;const int COLOR_TYPES = 6;

double sales[CAR_TYPES][COLOR_TYPES];

a) How many components does the array sales have?

b) What is the number of rows in the array sales?

c) What is the number of columns in the array sales?

d) To sum the sales by CAR_TYPES, what kind of processing is required?

e) To sum the sales by COLOR_TYPES, what kind of processing is required?

Page 24: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

24

Exercise #2

Consider the following declarations:

int beta[3][3];

What is stored in beta after each of the following statements executes?

a) for (i = 0; i < 3; i++)for (j = 0; j < 3; j++)

beta[i][j] = 0;

b) for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)

beta[i][j] = i + j;

Exercise #2

c) for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

beta[i][j] = i * j;

d) for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

beta[i][j] = 2 * (i + j) % 4;

Page 25: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

25

CONTENTS

2D array string manipulation

( Sort, Search)

Array of string

• Strings in C++ can be manipulated using

either the data type string or character arrays (C-strings)

• To declare an array of 100 components of type string:

string list[100];

Page 26: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

26

Array of string

• Character Arrays

Array operation

�Searching

cin>>target

for(int i = 0; i < ROW; i ++)

{

for(int x = 0; x < COL; x ++)

if(array[i][x] == target)

{

// operation

}

}

if (strcmp(target,name[i])==0)

Page 27: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

27

Array operation

�Sorting

void sort2DRow( int mark[ROW][COL]){

int hold;

for ( int row=0; row < ROW; row++ ){

for ( int col=0; col < COL; col++ ){

//bubble sort algorithm starts here

for ( int iteration=1; iteration < COL ; iteration++ ){

for ( int c=0; c < ( COL-iteration ) ; c++ ){

if ( mark[row][c] > mark[row][c+1] ){

hold = mark[row][c];

mark[row][c] = mark[row][c+1];

mark[row][c+1] = hold;

}

}

}

}

}

}

Array operation

�Sortingfor (int iteration=1; iteration<NO_OF_STUDENTS;

iteration++)

{

for (int index=0; index<NO_OF_STUDENTS-iteration;

index++)

{

if (strcmp(name[index],name[index+1]) > 0)

{

strcpy(temp,name[index]);

strcpy(name[index],name[index+1]);

strcpy(name[index+1],temp);

}

}

}

Page 28: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

28

• Another common application of two

dimensional arrays is to store an array of

strings.

• A string is an array of characters; so, an

array of strings is an array of arrays of

characters.

• The maximum size is the same for all the

strings stored in a two dimensional array

Two-Dimensional Array String Manipulation

• We can declare a two dimensional

character array of MAX_NUM_STR

of strings of MAX_SIZE of SIZE as follows:

char names[MAX_NUM_STR][MAX_SIZE];

Two-Dimensional Array String Manipulation

Page 29: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

29

• These Arrays can be initialized by putting the curly braces around

each row separating by a comma also each element of a matrix

should be separated by a comma.

char bravo [3] [3]= { 'c', 'a', 't' ,

'b', 'a', 't' ,

'g', 'a', 't' };

• Or

char months[12][10] = {"January", "February", "March",

"April", "May", "June",

"July", "August", "September”,"October", "November",

"December"};

Two-Dimensional Array String Manipulation

#include <iostream.h>

#include <string.h>

#include <conio.h>

#include <ctype.h>

void main()

{

char name[10][25];

char temp[25];

for(int i=0;i<=9;i++)

{

cout<<"\nEnter name"<<(i+1)<<": ";

cin>>name[i];

}

/******************************************/

cout<<"The sorted names are: "<<endl;

for (int iteration=0;iteration<=9;iteration++)

{

for(int k=0;k<=8;k++)

{

if (tolower(name[k][0])>tolower(name[k+1][0]))

{

strcpy(temp,name[k]);

strcpy(name[k],name[k+1]);

strcpy(name[k+1],temp);

}

}

}

Sorting an array of strings in alphabetical order

Page 30: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

30

CONTENTS

2D Array and function

Array and function

• Two-dimensional arrays are stored in row

order

• When declaring a two-dimensional array

as a formal parameter, can omit size of

first dimension, but not the second

• Example :

void displayOutput( int list[][6])

Page 31: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

31

Passing 2D Arrays as parameters to Functions

• When storing a two-dimensional array in the computer’s memory, the row order form is used

• This means that the first row is stored first, followed by the second row, which is followed by the third row and so on

• When declaring a two-dimensional array as a formal parameter, we can omit the size of the first dimension, but not the second

• The number of columns must be specified

Example 1#include <iostream.h>

#include <iomanip.h>

const int NUMBER_OF_ROWS=6;

const int NUMBER_OF_COLUMNS=5;

void printMatrix (int matrix [ ] [NUMBER_OF_COLUMNS],int NUMBER_OF_ROWS);

void sumRows (int matrix [ ] [NUMBER_OF_COLUMNS],int NUMBER_OF_ROWS);

void largestInRows (int matrix [ ] [NUMBER_OF_COLUMNS],int NUMBER_OF_ROWS);

void main() {

int board[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS] ={{23,5, 6, 15, 18},

{4, 16,24, 67,10},

{12,54,23, 76,11},

{ 1 ,12,34, 22,8},

{81, 54,32, 67,33},

{12, 34,76, 78, 9}};

printMatrix (board,NUMBER_OF_ROWS);

sumRows (board,NUMBER_OF_ROWS);

largestInRows (board,NUMBER_OF_ROWS);

}

Page 32: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

32

Example 1void printMatrix (int matrix [ ] [NUMBER_OF_COLUMNS],int noofRows)

{

int row,col;

for(row=0;row<noofRows;row++)

{

for(col=0;col<NUMBER_OF_COLUMNS;col++)

cout<<setw(5)<<matrix[row][col]<<" ";

cout<<endl;

}

}

void sumRows (int matrix [ ] [NUMBER_OF_COLUMNS],int noofRows)

{

int row,col;

int sum;

for(row=0;row<noofRows;row++)

{

sum=0;

for(col=0;col<NUMBER_OF_COLUMNS;col++)

sum=sum+matrix[row][col];

cout<<"Sum of row"<<(row+1)<<" = "<<sum<<endl;

}

}

Example 1

void largestInRows (int matrix [ ] [NUMBER_OF_COLUMNS],int noofRows)

{

int row,col;

int largest;

for(row=0;row<noofRows;row++)

{

largest=matrix[row][0];

for(col=0;col<NUMBER_OF_COLUMNS;col++)

if (largest < matrix[row][col])

largest = matrix[row][col];

cout<<"The largest element in column" <<(row+1) <<"="<<largest<<endl;

}

}

Page 33: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

33

Example 2

#include<iostream.h>

const int rowsize=2;

const int colsize=2;

void main()

{

int a[2][2]={1,2,3,4};

int row,col;

for(row=0;row<rowsize;row++)

for(col=0;col<colsize;col++)

cout<<a[row][col];

}

Example 2#include<iostream.h>

const int rowsize=2;

const int colsize=2;

void print(int a[][2]);

void main()

{

int a[2][2]={{1,2},{3,4}};

print(a);

}

void print(int a[][2])

{

int row,col;

for(row=0;row<rowsize;row++)

for(col=0;col<colsize;col++)

cout<<a[row][col];

}

Page 34: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

34

CONTENTS

Application of multi dimensional array

(Example : matrix, game)

Multidimensional Array

• Multidimensional array: collection of a

fixed number of elements (called

components) arranged in n dimensions (n

>= 1)

– Also called an n-dimensional array

• Declaration syntax:

• To access a component:

Page 35: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

35

Multidimensional Array

• When declaring a multidimensional array

as a formal parameter in a function

– Can omit size of first dimension but not other

dimensions

• As parameters, multidimensional arrays

are passed by reference only

• A function cannot return a value of the

type array

Tic Tac Toe

• #include <iostream.h>

• #include <conio.h>

• void main()

• {

• int i; /* Loop counter */

• int player; /* Player number - 1 or 2 */

• int go = 0; /* Square selection number for turn */

• int row; /* Row index for a square */

• int column; /* Column index for a square */

• int line; /* Row or column index in checking loop */

• int winner = 0; /* The winning player */

• char board[3][3] = { /* The board */

• {'1','2','3'}, /* Initial values are reference numbers */

• {'4','5','6'}, /* used to select a vacant square for */

• {'7','8','9'} /* a turn. */

• };

• char status;

• /* The main game loop. The game continues for up to 9 turns */

• /* As long as there is no winner */

• for( i = 0; i<9 && winner==0; i++)

• {

• /* Display the board */

• cout<<"\n\n";

• cout<<" "<<board[0][0]<<" | "<<board[0][1]<<" | "<<board[0][2]<<"\n";

• cout<<"---+---+---\n";

• cout<<" "<<board[1][0]<<" | "<<board[1][1]<<" | "<<board[1][2]<<"\n";

• cout<<"---+---+---\n";

• cout<<" "<<board[2][0]<<" | "<<board[2][1]<<" | "<<board[2][2]<<"\n";

Page 36: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

36

/* Get valid player square selection */

do

{

if (player==1)

status='X';

else

status='O';

cout<<"\nPlayer "<<player<<", please enter the number of the square"

"where you want to place your "<<status<<" ";

cin>>go;

row = --go/3; /* Get row index of square */

cout<<row;

column = go%3; /* Get column index of square */

cout<<column;

}while(go<0 || go>9 || board[row][column]>'9');

if(player == 1)

board[row][column] ='X';

else

board[row][column] ='O'; /* Insert player symbol */

Tic Tac Toe

/* Check for a winning line - diagonals first */

if((board[0][0] == board[1][1] && board[0][0] == board[2][2]) ||

(board[0][2] == board[1][1] && board[0][2] == board[2][0]))

winner = player;

else

/* Check rows and columns for a winning line */

for(line = 0; line <= 2; line ++)

if((board[line][0] == board[line][1] && board[line][0] == board[line][2])||

(board[0][line] == board[1][line] && board[0][line] == board[2][line]))

winner = player;

}

/* Game is over so display the final board */

cout<<"\n\n";

cout<<" "<<board[0][0]<<" | "<<board[0][1]<<" | "<<board[0][2]<<"\n";

cout<<"---+---+---\n";

cout<<" "<<board[1][0]<<" | "<<board[1][1]<<" | "<<board[1][2]<<"\n";

cout<<"---+---+---\n";

cout<<" "<<board[2][0]<<" | "<<board[2][1]<<" | "<<board[2][2]<<"\n";

/* Display result message */

if(winner == 0)

cout<<"\nHow boring, it is a draw\n";

else

cout<<"\nCongratulations, player"<< winner<<", YOU ARE THE WINNER!\n";

getch();

}

Tic Tac Toe

Page 37: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

37

Matrix Multiplication

Consider two matrices A and B with the following characteristics: the number of columns in A equals

the number of rows in B. These are conformable with respect to one another, and they can be

multiplied together to form a new matrix Z.

The expression

zij = ai1* b1j + ai2* b2j + ai3* b3j + ... aim* bnj

means "add the products obtained by multiplying elements in each i row of matrix A by elements in

each j column of matrix B". Figure 4 illustrates what we mean by this statement.

Matrix Multiplication

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

void main()

{

int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;

clrscr();

cout<<"Enter The Rows And Columns And Of The First Matrix:";

cin>>m>>n;

cout<<"\nEnter The Rows And Columns And Of The Second Matrix:";

cin>>p>>q;

cout<<"\nEnter Elements Of The First Matrix:\n";

for(i=0;i< m;i++)

{for(j=0;j< n;j++)

cin>>a[i][j];

}

cout<<"\nEnter Elements Of The Second Matrix:\n";

for(i=0;i< p;i++)

{for(j=0;j< q;j++)

cin>>b[i][j];

}

cout<<"The First Matrix Is:\n";

for(i=0;i< m;i++)

{for(j=0;j< n;j++)

cout<<a[i][j]<<" "; //print the first matrix

cout<<"\n";

}

Page 38: CSC138 STRUC PROG 2D.pptxhabibalbi.weebly.com/uploads/2/1/2/9/21292280/csc138_struc_prog_… · 12/7/2016 3 Introduction • Two-dimensional array : collection of a fixed number of

12/7/2016

38

Matrix Multiplication

cout<<"The Second Matrix Is:\n";

for(i=0;i< p;i++) // print the second matrix

{for(j=0;j< q;j++)

cout<<b[i][j]<<" ";

cout<<"\n";

}

if(n!=p)

{cout<<"Aborting!!!!!!/nMultiplication Of The Above Matrices Not Possible.";

exit(0);

}

else

{

for(i=0;i< m;i++)

{

for(j=0;j< q;j++)

{

c[i][j] = 0;

for(k=0;k< n;k++)

{

c[i][j] = c[i][j] + a[i][k] * b[k][j];

}

}

}

Matrix Multiplication

cout<<"\nMultiplication Of The Above Two Matrices Are:\n\n";

for(i=0;i< m;i++)

{

for(j=0;j< q;j++)

{

cout<<c[i][j]<<" ";

}

cout<<"\n";

}

}

getch();

}