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