Другие языки программирования и технологии

Двумерные массивы в С++

Дана матрица размером N. Найти сумму наименьших элементов ее нечетных строк и наибольших элементов ее четных строк.
#include <iostream>
#include <iomanip>
#include <random>
#include <algorithm>
using namespace std;
int main() {
const auto n = 4;
int matrix[n][n];
uniform_int_distribution<> uid(1, 100);
mt19937 gen{ random_device()() };
for (auto& row : matrix) for (auto& v : row) v = uid(gen);
for (auto& row : matrix) {
for (auto v : row) cout << setw(6) << v;
cout.put('\n');
}
int step = 0;
int smax = 0;
int smin = 0;
for (auto& row : matrix) {
++step & 1
? smin += *min_element(begin(row), end(row))
: smax += *max_element(begin(row), end(row));
}
cout
<< "\tSum max: " << smax << '\n'
<< "\tSum min: " << smin << '\n';
system("pause");
}
Павел Никульшин
Павел Никульшин
53 152
Лучший ответ
#include "stdio.h"

int main()
{
const int N = 3;
int s_min = 0;
int s_max = 0;

int A[N][N] = {
{1, 5, 3},
{2, 9, 1},
{7, 6, 4} };

for (int i = 0; i < N; i++)
{
if (i % 2 == 0)
{
int _max = A[i][0];
for (int j = 0; j < N; j++)
if (A[i][j] > _max)
_max = A[i][j];

s_max += _max;
}
else
{
int _min = A[i][0];
for (int j = 0; j < N; j++)
if (A[i][j] < _min)
_min = A[i][j];

s_min += _min;
}
}

printf("sum of min:%d\n", s_min);
printf("sum of max:%d", s_max);

return 0;