Two Dimensional Array

In this section, we will discuss about two dimensional array. Two dimensional array are known as matrix. They are indexed by two subscripts, one for row and another for column.

This program has four functions

  • Insert Elements – To add elements to a Matrix
  • Show Elements – To show elements of a Matrix
  • Add Matrix – To add two matrix
  • Get Determinant – To get the determinant of the Matrix

It is implemented in C++. The code is shown below

#include<iostream>
using namespace std;
void insert_elements(int arr[2][2]){
  cout<<"Enter the elements of matrix"<<endl;
  for(int i=0;i<2;i++){
    for(int j=0;j<2;j++){
      cout<<"arr["<<i<<"]["<<j<<"] : ";
      cin>>arr[i][j];
    }
  }
}
void show_elements(int arr[2][2]){
  cout<<"The elements of matrix are "<<endl;
  for(int i=0;i<2;i++){
    for(int j=0;j<2;j++){
      cout<<arr[i][j]<<" ";
    }
    cout<<endl;
  }
}
void get_determinant(int arr[2][2]){
  cout<<"The determinant is ";
  cout<<(arr[0][0]*arr[1][1]-arr[0][1]*arr[1][0])<<endl;
}
void add_matrix(int a[2][2],int b[2][2],int c[2][2]){
  cout<<"Adding two matrix"<<endl;
  for(int i=0;i<2;i++){
    for(int j=0;j<2;j++){
      c[i][j] = a[i][j]+b[i][j];
    }
  }
  show_elements(c);
}
int main(){
  int a[2][2],b[2][2],c[2][2];
  insert_elements(a);
  show_elements(a);
  get_determinant(a);
  cout<<"Second Matrix"<<endl;
  insert_elements(b);
  show_elements(b);
  add_matrix(a,b,c);
  return 0;
}

The output of the program is shown below

output of the program. 2-D Matrix
output of the program. 2-D Matrix

Leave a Reply