Tuesday, 19 May 2015

Array Program To Add and Subtract Two Matrices

Add Two Matrices in C++
Problem Description: Write a program in c++ that will add and subtract two matrices.

This program adds two matrices by using arrays in c++. The program will ask you to enter the number of rows and columns and then to enter the value of each row and column. After that this will add or subtract by your choice.

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
    int rows,cols;
    int choice;
string ch;    
    do{
    cout<<"Enter number of rows ::)) "; cin>>rows;
    cout<<"Enter number of columns :: )) "; cin>>cols;
    
    int matrix1[rows][cols],matrix2[rows][cols],matrixsum[rows][cols],matrixsub[rows][cols],i,j;    
    cout<<"\t\t***YOU HAVE TO ENTER THE DATA OF 2 MATRICES ***\n\n";
    cout<<"\tEnter matrix 1 data \n";
    for(i=0;i<rows;i++)
    {
     for(j=0;j<cols;j++)
     {
      // cout<<"[ "<<i+1<<"]"<<"["<<j+1"]=";
       cout<<"Enter row "<<i+1<<"column "<<j+1<<" =)) ";
       cin>>matrix1[i][j];
       }
       }
     cout<<"\tEnter matrix 2 data \n";
     for(i=0;i<rows;i++)
    {
     for(j=0;j<cols;j++)
     {
      // cout<<"[ "<<i+1<<"]"<<"["<<j+1"]=";
       cout<<"Enter row "<<i+1<<"column "<<j+1<<" =)) ";
       cin>>matrix2[i][j];
       }
       } 
    do{
    cout<<"\n\t\t\t*** CHOICE ***\n";
    cout<<"\tSelect 1 for (2matrices) addition \n\t"
    <<"Select 2 for (2 matrices) subtraction\n "; 
    cout<<"\tEnter your choice ::))"; cin>>choice;
    switch(choice)
    {  
      case 1:
       for(i=0;i<rows;i++)
       {
         for(j=0;j<cols;j++)
         {
            matrixsum[i][j]=matrix1[i][j]+matrix2[i][j];
            cout<<matrixsum[i][j]<<"\t";
         }
            cout<<"\n";
         }
         break;
       case 2:
          for(i=0;i<rows;i++)
           {
            for(j=0;j<cols;j++)
            {
            matrixsub[i][j]=matrix1[i][j]-matrix2[i][j];
            
            cout<<matrixsub[i][j]<<"\t";
            }
            cout<<"\n";
            }
          
           break;
           }
            cout<<"DO U WANT TO DO NEXT OPERATION"; cin>>ch;
       }while(!(ch=="no"||ch=="NO"));
       
            cout<<"DO U WANT TO DO AN OTHER OPERATION ::))) "; cin>>ch;
            }
            while(!(ch=="no"||ch=="NO"));
            system("cls");
    system("pause");
    return 0;
    }

0 comments:

Post a Comment