Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Slide 22:

A 2-D array represents an n by m matrix, and since operations can be performed to matrices in this example
we will show how to Add or Substract matrices.

First we initialize three arrays using the constants ROW and COL with 2 and 3 values respectively.

#define ROW 2
#define COL 3

We proceed with populating the matrices mat1 and mat2 with integer values by looping across the Rows and
then looping across the Columns. We do that using a for loop where the index starts at 0, until ROW minus 1
since index i is less than ROW, and index j is less than COL.

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


{
for(j = 0; j < COL; j++)
{
printf(“Enter a[%d][%d]: “, i, j);
scanf(“%d”, &mat1[ i ][ j ])

it is important to note that the indices go from left to right, thus we have mat1[ i ][ j ]

Slide 23:

To add matrices mat1 and mat2, we simply add the respective elements. We do that by once again looping
across the Rows and looping across the Columns using two for loops, and add the respective i and j indices of
mat1 and mat2 and assign it to mat3 using the same indices once again.

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


{
for(j = 0; j < COL; j++)
{
mat3[ i ][ j ] = mat1[ i ][ j ]+ mat2[ i ][ j ]

Slide 24:

For example, we entered the following values in the following indices: For the first matrix, we have:

a[0][0] or Row 0, Col 0 = 12,


a[0][1] or Row 0, Col 1 = 32
a[0][2] or Row 0, Col 2 = 13 and so on and so forth

This represents the values of a 2 by 3 matrix:

12 32 13
35 54 35
And the second matrix as:

a[0][0] or Row 0, Col 0 = 57,


a[0][1] or Row 0, Col 1 = 64
a[0][2] or Row 0, Col 2 = 58 and so on and so forth

This represents the values of a 2 by 3 matrix :

57 64 58
72 84 29
Slide 25:

What this shows is that we can get the sum of two matrices by looping across the rows and columns
respectively. Do note that this follows we can only add and subtract matrices if and only if the matrices are
the same size.

You might also like