Monday, 26 January 2015

Cpp Program for implementing matrix addition


In this post we will implement addition of two matrices with Cpp Programming.
Cpp Programming - Matrix Addition

PROGRAM :
#include <iostream>

using namespace std;

int main()
{
    int i,j,rows1,rows2,columns1,columns2;
    cout << "Enter order of matrix 1 :\t";
    cin >> rows1;
    cin >> columns1;
    cout << "Enter order of matrix 2  :\t";
    cin >> rows2;
    cin >> columns2;
    int matrix1[rows1][columns1],matrix2[rows2][columns2],result[rows1][columns1];
    if(rows1 != rows2 || columns1 != columns2 )
    {
        cout << "Both matrices must have same  of order ";
        return 0;
    }

    cout << "\nEnter elements of matrix 1:\n";
    for(i=0; i<rows1; i++)
    {
        for(j=0; j<columns1; j++)
        {
            cout << "Enter element m"<<i+1<<j+1 << "\t";
            cin >> matrix1[i][j];

        }
    }
    cout << "\nEnter elements of matrix 2:\n";
    for(i=0; i<rows2; i++)
    {
        for(j=0; j<columns2; j++)
        {
            cout << "Enter element m"<<i+1<<j+1 << "\t";
            cin >> matrix2[i][j];

        }
    }
    cout << "\nMATRIX 1 is " << endl;
    for (i = 0; i < rows1; i++)
    {
        for (j = 0; j < columns1; j++)
        {
            cout <<  matrix1[i][j] << ":\t";
        }
        cout << "\n";
    }
    cout << "\nMATRIX 2 is" << endl;
    for (i = 0; i < rows2; i++)
    {
        for (j = 0; j < columns2; j++)
        {
            cout << matrix2[i][j]<< ":\t";
        }
        cout << "\n";
    }
    for (i = 0; i < rows1; i++)
    {
        for (j = 0; j < columns1; j++)
        {
            result[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
    cout << "\nThe Addition of two Matrices is : "<<endl;
    for (i = 0; i < rows1; i++)
    {
        for (j = 0; j < columns1; j++)
        {
            cout << result[i][j] << "\t";
        }
        cout << "\n";
    }
    return 0;
}

OUTPUT : 
Cpp Programming - Matrix Addition

No comments:

Post a Comment