answersLogoWhite

0

#include<iostream>

#include<array>

#include<time.h>

int main()

{

srand ((unsigned)time(nullptr));

// Matrix: 5 rows, 4 columns

const size_t rows = 5;

const size_t cols = 4;

std::array<std::array<size_t, cols>, rows> matrix;

// Initialise matrix with random values (range: 0 to 9)

for (size_t row=0; row<rows; ++row)

for (size_t col=0; col<cols; ++col)

matrix[row][col] = rand() % 10;

// Print matrix.

std::cout << "Matrix:\n\n";

for (size_t row=0; row<rows; ++row)

{

for (size_t col=0; col<cols; ++col)

std::cout << matrix[row][col] << '\t';

std::cout << std::endl;

}

std::cout << std::endl;

// Initialise array for row and column sums

std::array<size_t, rows> row_sum {};

std::array<size_t, cols> col_sum {};

// Calculate sums:

for (size_t row=0; row<rows; ++row)

{

for (size_t col=0; col<cols; ++col)

{

row_sum[row] += matrix[row][col];

col_sum[col] += matrix[row][col];

}

}

// Print sums:

for (size_t row=0; row<rows; ++row)

std::cout << "Row " << row << " sum = " << row_sum[row] << std::endl;

std::cout << std::endl;

for (size_t col=0; col<cols; ++col)

std::cout << "Col " << col << " sum = " << col_sum[col] << std::endl;

std::cout << std::endl;

}

User Avatar

Wiki User

10y ago

What else can I help you with?

Related Questions