Categories

Tools

bitdefender

1&1 Web Hosting

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

Posted in C++ by MdmSoft

If our work has been of help, you can help us with a small donation...
Our programmers will thank you!



All information contained in this web site are the property of MdmSoft. The information is provided "as is", MdmSoft will not be liable for any misuse of the code contained in these pages, nor can it be for inaccuracies, grammatical errors or other factors that may have caused damage or lost earnings. MdmSoft is not responsible for the content of comments posted by users.
The examples in this area have the educational and demonstration purposes only, and may be copied only for your reference, but cannot be used for commercial purposes, or for any other purpose, without the express written consent of MdmSoft.
MdmSoft also reserves the right to change, without notice, to your liking this web site, the pages and its sections, and may suspend temporarily or definitely the various services included on this site.
While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy.