Subtraction using Two Dimensional Array in C++


This is a C++ program that subtracts two matrices. Here's how the program works:

  • The program prompts the user to enter the number of rows and columns for the matrices.
  • The program calls the sum function, passing the number of rows and columns as arguments.
  • The sum function creates three 2D arrays: m1, m2, and s. m1 and m2 are used to store the two matrices entered by the user, and s is used to store the difference of the two matrices.
  • The program prompts the user to enter the elements of the first matrix row by row, and stores the values in the m1 array.
  • The program prompts the user to enter the elements of the second matrix row by row, and stores the values in the m2 array.
  • The sum function subtracts the corresponding elements of m2 from m1 to create s.
  • Finally, the sum function prints out the elements of s as a single row, with each element separated by a space.

Overall, this program performs the matrix subtraction operation, which is the same as matrix addition but with subtraction of corresponding elements. One potential improvement to the program would be to add error handling in case the user enters invalid inputs, such as non-numeric values or matrices with different dimensions.

Source Code

#include<iostream>
using namespace std;
void sum(int, int);
int main()
{
  int row,col;
  cout<<"\nEnter the number of rows: ";
  cin>>row;
  cout<<"\nEnter the number of column: ";
  cin>>col;
  sum(row,col);
  return 0;
}
void sum(int r, int c)
{
  int m1[r][c], m2[r][c], s[r][c];
  cout<<"Enter the elements of first 1st matrix: ";
  for(int i=0;i<r;i++)
  {
    for(int j=0;j<c;j++)
    {
      cin>>m1[i][j];
    }
  }
  cout<<"Enter the elements of first 1st matrix: ";
  for(int i=0;i<r;i++)
  {
    for(int j=0;j<c;j++)
    {
      cin>>m2[i][j];
    }
  }
  cout<<"Output: ";
  for(int i=0;i<r;i++)
  {
    for(int j=0;j<c;j++)
    {
      s[i][j]=m1[i][j]-m2[i][j];
      cout<<s[i][j]<<" ";
    }
  }
}
To download raw file Click Here

Output

Enter the number of rows: 2
Enter the number of column: 2
Enter the elements of first 1st matrix: 1
2
3
4
Enter the elements of first 1st matrix: 5
6
7
8
Output: -4 -4 -4 -4

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples