You are on page 1of 2

Write a menu-driven C++ program for matrix manipulation.

The program should implement the following tasks: Initialize an NxN matrix with random numbers in the range 1-9. Print an NxN matrix in tabular form. Add two NxN matrices. Multiply two NxN matrices.

#include "stdafx.h" #include<iostream> using namespace std; int r,c,x,y, n1[10][10], n2[10][10]; int add[10][10], multi[10][10]; int main() { void print(); void addition(); void multiplication(); cout<<"Enter the number of rows: "; cin>>r; cout<<"Enter the number of columns: "; cin>>c; cout<<"\nEnter the elements of first matrix:\n"; for(x=0 ; x<r ; x++) { for(y=0 ; y<c ; y++) { n1[x][y] = rand()%9+1; cout<<n1[x][y]<<" "; } cout<<endl; } cout<<"\nEnter the elements of second matrix:\n"; for(x=0; x<r ; x++) { for(y=0 ; y<c ; y++) { n2[x][y] = rand()%9+1; cout<<n2[x][y]<<" "; } cout<<endl; } cout<<"\nChoose Option from the Menu:"; cout<<"\n1. Matrix Print"; cout<<"\n2. Matrix Addition"; cout<<"\n3. Matrix Multiplication"; cout<<"\nEnter Your Choice: "; cin>>x; switch(x) { case 1: print(); break; case 2: addition(); break; case 3: multiplication(); break; default: cout<<"\nInvalid Choice"; } return 0; }

void print() { cout<<"\nFirst Matrix in Tabular Form: "<<endl; for(x=0 ; x<r ; x++) { for(y=0 ; y<c ; y++) cout<<n1[x][y]<<"\t"; cout<<endl; } cout<<"\nSecond Matrix in Tabular Form: "<<endl; for(x=0 ; x<r ; x++) { for(y=0 ; y<c ; y++) cout<<n2[x][y]<<"\t"; cout<<endl; } } void addition() { for(x=0 ; x<r ; x++) { for(y=0 ; y<c ; y++) add[x][y] = n1[x][y] + n2[x][y]; } cout<<"\nSum of Matrices:\n"; for(x=0 ; x<r ; x++) { for(y=0 ; y<c ; y++) cout<<add[x][y]<<"\t"; cout<<endl; } } void multiplication() { for(x=0 ; x<r ; x++) { for(y=0 ; y<c ; y++) multi[x][y] = n1[x][y] * n2[x][y]; } cout<<"\nMultiplication of Matrices: \n"; for(x=0 ; x<r ; x++) { for(y=0 ; y<c ; y++) cout<<multi[x][y]<<"\t"; cout<<endl; } }