Multi-dimensional Array in C - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Multi-dimensional Array in C

Share This

Let us consider that we have to work with a matrix. How can this matrix be stored in the program? Here, the solution is a two-dimensional array.

An array can be of different dimensional, one, two, or more than two as per our requirement. To work with a matrix, we need a two-dimensional array. To store an image (photograph), a two-dimensional array is used. But in many scientific applications, n-dimensional arrays are used.

If you need a multi-dimensional array, you can declare the array mentioning multiple dimensions as shown below.

  // for two dimensional array
  int arr[10][20];
  // for three dimensional array
  int arr[10][20][10];

Let us try to understand the memory allocation for multi-dimensional arrays. In the following program, a two-dimensional array has been declared, that has 3 rows and 5 columns. If you look at the memory allocation, you will notice that the memory allocation is contiguous. Even though there are 3 rows, the memory allocation is contiguous spaces. It's a single chunk of memory for 15 elements (3 rows x 5 columns). It depicts that a multi-dimensional array is a logical representation, but physical memory allocation is linear.

#include <stdio.h> int main() { int numbers[3][5], i, j; for(i = 0; i < 3; i++) { for(j = 0; j < 5; j++) { printf(" %u ", &numbers[i][j]); } } return 0; }





Matrix Multiplication


In the following program, we will show you, how to use a two-dimensional array. In this program, we will calculate the resultant matrix res, by multiplying two matrices, namely mat1 and mat2.

Code of matrix_multiplication.c
#include <stdio.h> #include <stdlib.h> int main() { int m, n, p, q, i, j, k; int mat1[10][10], mat2[10][10], res[10][10]; printf("Enter order of first matrix: "); scanf("%d %d", &m, &n); printf("Enter order of second matrix: "); scanf("%d %d", &p, &q); if(n == p) { printf("Enter elements of matrix 1: "); for(i = 0; i < m; i++) { for(j = 0; j < n; j++) { scanf("%d", &mat1[i][j]); } } printf("Enter elements of matrix 2: "); for(i = 0; i < p; i++) { for(j = 0; j < q; j++) { scanf("%d", &mat2[i][j]); } } for(i = 0; i < m; i++) { for(j = 0; j < q; j++) { res[i][j] = 0; for (k = 0; k < n; k++) { res[i][j] = res[i][j] + mat1[i][k] * mat2[k][j]; } } } printf("The resultant matrix is : \n"); for(i = 0; i < m; i++) { for(j = 0; j < n; j++) { printf("%d ", res[i][j]); } printf("\n"); } } else { printf("Invalid input..."); } return 0; }




Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.