Categories

Tools

bitdefender

1&1 Web Hosting

Example of using matrices and vectors of integers with C++


Exercise: An matrix of size 3 x 6 contains integers. Write a program in C++ that determines the minimum of the values contained in each row of the array, and store these values in a vector. Print out the result.

#include <iostream>

int main ()
{  
    // Initialize random number generator
    srand(time(NULL));
    
    // Define the dimension of the matrix
    const int R = 3;
    const int C = 6;
    
    // Declare a matrix and a vector
    int m [R][C];
    int v [R];
    
    // 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()%50)+1;
        }
    }
    
    // Showing the contents of the matrix
    printf( "The matrix: \n");
    for(int i=0; i<R; i++)
    {
        for(int j=0; j<C; j++)
        {
        printf( "%d\t", m[i][j]);
        }
        printf( "\n");
    }
    
    printf( "\n");
    
    // Calculating the minimum of each row of the matrix
    int min;
    for(int i=0; i<R; i++)
    {
            min = 100;
            for(int j=0; j<C; j++)
            {
             if (m[i][j] < min) 
                min = m[i][j];
            }
            // Save the minimum value found in the i-th element of the vector
            v[i] = min;
    }
    
    printf( "\n");
    
    // Showing the contents of the vector
    printf( "The array that contains the minimum values of each row of the matrix: \n");
    for(int i=0; i<R; i++)
    {
            printf( "%d \n", v[i]);
    }
        
    return 0;
}

This is the result:

The matrix:
19    39    26    35    45   
37    3      15    27    5   
43    12    40    26    5   
31    25    24    30    14   
26    42    13    20    48   


The array that contains the minimum values of each row of the matrix:
19
3
5
14
13

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.