You are on page 1of 38

2D ARRAYS

• 2D arrays: An array is a contiguous block of memory. A 2D array of size m by n is defined as


• int A[m][n];
• The number of bytes necessary to hold A is m*n*sizeof(int). The elements of A can be accessed
using A[i][j] where i can be
• thought of as the row index and j can be thought of as the column index. Now we take a look at
how 2D arrays are storing
• their elements. For example,
• #define n 2
• #define m 3
• int A[n][m];
• or can be defined and initialized as
• int A[2][3]={{1,2,3},{4,5,6}};
• Array of Pointers: C arrays can be of any type. We define array of ints,
chars, doubles etc. We can also define an array of
• pointers as follows. Here is the code to define an array of n char
pointers or an array of strings.
• char* A[n];
• each cell in the array A[i] is a char* and so it can point to a character.
• To assign a string to each A[i] we can do the following:
• A[i] = malloc(length_of_string + 1);
arr2d[row][col] =

*(*(arr2d + row) + col)


Example 1
Example 2
Example 3
PROBLEM 1.
• Write a function matrixSum(), that takes as parameters two matrices
A and B of doubles, and returns a new matrix obtained by summing
corresponding elements of A and B. We assume that A and B have the
same dimensions.
Problem 1 – sol 2
PROBLEM 2
• Write a function matrixProduct(), that takes as parameters two
matrices A and B of doubles and returns a newmatrix obtained as the
product of A and B. Assume that the matrices are square, i.e., they
have the same numbers of rows and columns, and that A and B have
the same dimensions.
SOLUTION:
• https://www.programiz.com/c-programming/examples/matrix-multipl
ication

• https
://www.programmingsimplified.com/c-program-multiply-matrices
Problem 3.
• Write a function matrixSumRows(), that takes as parameter a matrix
and returns an array with one element for each row of the matrix; the
element of index i of the array must be equal to the sum of the
elements of row i of the matrix.
PROBLEM 4.
• Write a function transposeMatrix() that returns a new matrix that is
the transpose of the matrix M. We recall that the transpose of a
matrix M is obtained by exchanging the rows with the columns, which
corresponds to exchange Mij with Mji], for each pair of valid indexes i
and j.
PROBLEM 5.
• A matrix M is said to be symmetric if it is square (i.e., has the same
number of rows and columns) and Mij is equal to Mji, for each pair of
valid indexes i and j. Write a symmetricMatrix() that returns true if the
matrix M is symmetric, and false otherwise.

You might also like