BIT102 ยท 2078 ยท 5 marks
What do you mean by multi-dimensional array? Write a program to display the sum of two mxn matrices.
What do you mean by multi-dimensional array? Write a program to display the sum of two mxn matrices. [5]
C ProgrammingChapter 6: Arrays and StringsMulti-dimensional arrays
Quick answer
A multi-dimensional array is an array that has more than one dimension (index). It can be thought of as an array of arrays. The most common form is the two-dimensional (2D) array, which represents data in rows and columns (like a matrix).
Multi-Dimensional Array
Definition
General syntax in C:
data_type array_name[size1][size2]...[sizeN];
For a 2D array (matrix):
int matrix[m][n]; // m rows and n columns
Elements are accessed using two indices: matrix[i][j] where i is the row index and j is the column index.
Program to Display the Sum of Two M x N Matrices
#include <stdio.h>
int main() {
int m, n, i, j;
int A[10][10], B[10][10], C[10][10];
// Input dimensions
printf("Enter number of rows (m): ");
scanf("%d", &m);
printf("Enter number of columns (n): ");
scanf("%d", &n);
// Input elements of matrix A
printf("\nEnter elements of Matrix A (%dx%d):\n", m, n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("A[%d][%d]: ", i, j);
scanf("%d", &A[i][j]);
}
}
// Input elements of matrix B
printf("\nEnter elements of Matrix B (%dx%d):\n", m, n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("B[%d][%d]: ", i, j);
scanf("%d", &B[i][j]);
}
}
// Calculate sum: C = A + B
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
// Display the result matrix C
printf("\nSum Matrix C = A + B:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d\t", C[i][j]);
}
printf("\n");
}
return 0;
}
Sample Output
Enter number of rows (m): 2
Enter number of columns (n): 2
Enter elements of Matrix A (2x2):
A[0][0]: 1
A[0][1]: 2
A[1][0]: 3
A[1][1]: 4
Enter elements of Matrix B (2x2):
B[0][0]: 5
B[0][1]: 6
B[1][0]: 7
B[1][1]: 8
Sum Matrix C = A + B:
6 8
10 12
Key Points
| Concept | Detail |
|---|---|
| Declaration | int A[10][10] declares a 2D array |
| Access | A[i][j] accesses element at row i, column j |
| Nested loops | Outer loop for rows, inner loop for columns |
| Addition rule | C[i][j] = A[i][j] + B[i][j] for each element |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.