How to determine the minimum value and the maximum value in a matrix of integers with c++
Exercise: An matrix of size 5 x 5 contains integers. Write a program in C++ that determines the minimum and the maximum of the values contained in the Matrix. Print out the contents of the matrix, marking the minimum values with the sign - and maximum values with the sign +
#include <iostream>
int main ()
{
// Initialize random number generator
srand(time(NULL));
// Define the dimension of the matrix
const int R = 5;
const int C = 5;
// Declare a matrix and a vector
int m [R][C];
// Fill the matrix with random values from 1 to 50
for(int i=0; i<R; i++)
{
for(int j=0; j<C; j++)
{
m[i][j] = (rand()%90)+10;
}
}
// Calculating the minimum and maximum of the matrix
int min = 100;
int max = 0;
for(int i=0; i<R; i++)
{
for(int j=0; j<C; j++)
{
if (m[i][j] < min)
min = m[i][j];
if (m[i][j] > max)
max = m[i][j];
}
}
// Showing the contents of the matrix
// Marking the minimum values with the sign -
// Marking the maximum values with the sign +
for(int i=0; i<R; i++)
{
for(int j=0; j<C; j++)
{
if(m[i][j]==min)
printf( "%d-\t", m[i][j]);
else if(m[i][j]==max)
printf( "%d+\t", m[i][j]);
else
printf( "%d\t", m[i][j]);
}
printf( "\n");
}
return 0;
}
This is the result:
90 65 45 43 45
10- 52 95 21 87
84 95 94 19 79
35 35 55 87 12
65 25 98+ 31 58