In: Computer Science
C++ Program:
Create a 3x3 matrix of int values. Implement five functions, each expecting the matrix as parameter input. The first function must use a nested loop to prompt a user to enter each value. Show the indices when prompting for input and populate the matrix with these values. The second function outputs the matrix and formats the output to align all columns and rows to accommodate values up to 1000. The third function finds and returns the minimum value in the matrix. The fourth function finds and returns the maximum value in the matrix. The fifth function calculates and returns the average of values in the matrix. Call each function from the main and output the minimum, maximum, and average values returned by the functions in the main.
Example:
Input Value at 0, 0: 7 Value at 0, 1: 2 Value at 0, 2: 10 Value at 1, 0: 1 Value at 1, 1: 12 Value at 1, 2: 2 Value at 2, 0: 3 Value at 2, 1: 14 Value at 2, 2: 19 Matrix: [ 7, 2, 10], [ 1, 12, 2], [ 3, 14, 19]; Min: 1 Max: 19 Avg: 7
SOLUTION-
I have solve the problem in C++ code with comments and screenshot
for easy understanding :)
CODE-
//c++ code
#include <iostream>
#include <iomanip>
using namespace std;
//function to read input from user
void readInputs(int (&matrix)[3][3])
{
cout << "Input:-"<<endl;
//reading inputs deom user
for(int i=0;i<3;i++)
for(int j=0;j<3;j++){
cout << "value at "<< i << "," << j
<< ": "; //values
cin >> matrix[i][j];
}
}
//function to print matrix
void printMatrix(int (&matrix)[3][3])
{
cout << "\nMatrix:"<<endl;
//printing matrix
for(int i=0;i<3;i++){
cout << "[";
for(int j=0;j<3;j++){
if(j<2)
cout << setw(4) << right << matrix[i][j] <<
",";
else
cout << setw(4) << right << matrix[i][j];
}
if(i<2)
cout << "]," << endl;
else
cout << "];" << endl;
}
}
//find mazimum from matrix
int findMaximum(int (&matrix)[3][3])
{
int max = -9999;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++){
if(matrix[i][j] > max)
max = matrix[i][j];
}
return max;
}
//find Minimum from matrix
int findMinimum(int (&matrix)[3][3])
{
int min = 99999;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++){
if(matrix[i][j] < min)
min = matrix[i][j];
}
return min;
}
//find Average from matrix
int Average(int (&matrix)[3][3])
{
int sum = 0;
float avg;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++){
sum += matrix[i][j] ;
}
avg=sum/9;
return avg;
}
//main code
int main()
{
int matrix[3][3];
readInputs(matrix);
printMatrix(matrix);
//print min,max,avg for matrix element
cout << "\nMinimum : " << findMinimum(matrix)
<<endl;
cout << "Maximum : " << findMaximum(matrix)
<<endl;
cout << "Average : " << Average(matrix)
<<endl;
return 0;
}
SCREENSHOT-
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL
SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------