Addition using Two Dimensional Array in C++


This is a C++ program that reads two matrices from the user and adds them element-wise to create a third matrix. Here's how the program works:

  • The program first prompts the user to enter the number of rows and columns for the matrices.
  • The program then prompts the user to enter the elements of the first matrix row by row, and stores the values in a 2D array called m1.
  • The program then prompts the user to enter the elements of the second matrix row by row, and stores the values in a 2D array called m2.
  • The program then creates a third 2D array called sum, and adds the corresponding elements of m1 and m2 to create sum.
  • Finally, the program prints out the elements of sum as a single row, with each element separated by a space.

The program assumes that both matrices have the same number of rows and columns. 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;
int main()
{
  int row,col,m1[10][10],m2[10][10],sum[10][10];
  cout<<"\nEnter the number of rows: ";
  cin>>row;
  cout<<"\nEnter the number of column: ";
  cin>>col;
  cout<<"\nEnter the elements of first 1st matrix: ";
  for(int i=0;i<row;i++)
  {
    for(int j=0;j<col;j++)
    {
      cin>>m1[i][j];
    }
  }
  cout<<"Enter the elements of second 2nd matrix: ";
  for(int i=0;i<row;i++)
  {
    for(int j=0;j<col;j++)
    {
      cin>>m2[i][j];
    }
  }
  cout<<"Output: ";
  for(int i=0;i<row;i++)
  {
    for(int j=0;j<col;j++)
    {
      sum[i][j]=m1[i][j]+m2[i][j];
      cout<<sum[i][j]<<" ";
    }
  }
  return 0;
}
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 second 2nd matrix: 5
6
7
8
Output: 6 8 10 12

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