You are on page 1of 5

CS201

Assignment no:2
Solution
19/June/2021
Problem Statement

A matrix is given in source data. You have to write user defined functions and create a menu in C++ keeping
in mind the following requirements:

1. Press 1 to display the matrix and its transpose.


(Hint: Transpose of a matrix can be achieved by changing its rows into columns or columns
into rows.)

2. Press 2 to find adjoint and determinant of the matrix.


(Hint: To find adjoint of a matrix, we change the places of its diagonal elements and the
signs of non-diagonal elements; To find determinant of matrix, we subtract the product
of non-diagonal elements from the product of diagonal elements.)

3. Press any other key to exit.

Source data:
(Use two dimensional array to store following matrix)
8 −4
[ ]
−6 2
Instructions to write C++ program:
➢ Write functions to display the matrix; find transpose, adjoint and determinant of the matrix.
Following function names should be used for consistency.
To display matrix showMatrix ( );

To show transpose showTranspose ( );

To show adjoint showAdjoint ();

To find determinant calculateDeterminant ();


Solution:
#include<iostream>
using namespace std;

void originalMatrix (int arr [2][2])


{
arr [0][0] = 8;
arr [0][1] = -4;
arr [1][0] = -6;
arr [1][1] = 2;
}

void showMatrix (int arr [2][2])


{ cout<<endl;
for (int i = 0; i < 2; i++)
{for (int j = 0; j < 2; j++)
{ cout<<arr[i][j] <<"\t";
}
cout<<endl;
}

cout<<endl;
} // end of showMatrix function

void showTranspose (int arr [2][2])


{ int temp;
temp= arr [0][1];
arr [0][1] =arr [1][0];
arr [1][0] =temp;
cout<<"Transpose of the given matrix is"<< endl;
showMatrix(arr);
} // end of showTranspose function

void showAdjoint (int arr [2][2])


{
int temp;
temp=arr [0][0];
arr [0][0] = arr [1][1];
arr [1][1] = temp;
arr [0][1] = (-1) *(arr [0][1]);
arr [1][0] = (-1) * (arr [1][0]);
cout<<"Adjoint of the given matrix is"<<endl;
showMatrix(arr);
} // end of showAdjoint function

void calculateDeterminant (int arr [2][2])


{
int det;
de t= (arr [0][0]) * (arr [1][1]) - (arr [0][1]) * arr [1][0];
cout << "Determinant of the given matrix is " << det <<endl;
} // end of calculateDeterminant function

int main ()
{
int arr [2][2];
arr [0][0] = 8;
arr [0][1] = -4;
arr [1][0] = -6;
arr [1][1] = 2;
int ch;

do {
cout<<"Enter your choice"<<endl;
cout<<"Press 1 to display the matrix and its transpose. "<<endl;
cout<<"Press 2 to find adjoint and determinant of the matrix."<<endl;
cout<<"Press any other key to exit."<<endl;

cin>>ch;

if(ch==1)
{
cout << "Matrix is";
showMatrix(arr);
showTranspose(arr);
}
else if (ch==2)
{
originalMatrix(arr);
showAdjoint(arr);
originalMatrix(arr);
calculateDeterminant(arr);
cout<<endl;

}
else
{
return 0;
}
}
while(true);
return 0;
}

You might also like