Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Array

2D Array

Patterns

Excersises


C Program to Add Two Matrices Using Multi-dimensional Arrays


A two-dimensional (2D) array this program adds two 2x2 matrices and displays the resultant matrix.

  • array1 and array2 are two 2x2 matrices with predefined values.
  • A third matrix, result, is declared to store the sum of the corresponding elements of array1 and array2.
  • A nested for loop iterates over rows and columns of the matrices.
  • Each element of array1 is added to the corresponding element of array2, and the result is stored in result.
  • Another nested for loop iterates over the result matrix to print its contents.
Example : add_two_2darray.c
#include <stdio.h>

int main() {
  int rows, cols;
  
  // Input dimensions of the matrices
  printf("Enter the number of rows: ");
  scanf("%d", &rows);
  printf("Enter the number of columns: ");
  scanf("%d", &cols);
  
  int matrix1[rows][cols], matrix2[rows][cols], result[rows][cols];
  
  // Input elements of the first matrix
  printf("Enter elements of the first matrix:\n");
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("Enter element at [%d][%d]: ", i, j);
      scanf("%d", &matrix1[i][j]);
    }
  }
  
  // Input elements of the second matrix
  printf("Enter elements of the second matrix:\n");
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("Enter element at [%d][%d]: ", i, j);
      scanf("%d", &matrix2[i][j]);
    }
  }
  
  // Add the two matrices
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      result[i][j] = matrix1[i][j] + matrix2[i][j];
    }
  }
  
  // Display the resulting matrix
  printf("\nResultant Matrix after Addition:\n");
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("%d ", result[i][j]);
    }
    printf("\n");
  }
  
  return 0;
}

Output:

Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first matrix:
Enter element at [0][0]: 1
Enter element at [0][1]: 2
Enter element at [1][0]: 3
Enter element at [1][1]: 4
Enter elements of the second matrix:
Enter element at [0][0]: 5
Enter element at [0][1]: 6
Enter element at [1][0]: 7
Enter element at [1][1]: 8

Resultant Matrix after Addition:
6 8
10 12