11. Написать функцию для нахождения суммы элементов для каждой строки двумерного динамического массива. Поменять местами строки с максимальным и минимальным значением суммы.
#include <iostream>
#include <limits>
void findSumOfRows(int** matrix, int numRows, int numCols) {
if (numRows <= 0 || numCols <= 0) {
std::cout << "Invalid matrix dimensions." << std::endl;
return;
}
int* rowSums = new int[numRows];
for (int i = 0; i < numRows; ++i) {
int sum = 0;
for (int j = 0; j < numCols; ++j) {
sum += matrix[i][j];
}
rowSums[i] = sum;
std::cout << "Sum of row " << i + 1 << ": " << sum << std::endl;
}
int minSumIndex = 0;
int maxSumIndex = 0;
for (int i = 1; i < numRows; ++i) {
if (rowSums[i] < rowSums[minSumIndex]) {
minSumIndex = i;
}
if (rowSums[i] > rowSums[maxSumIndex]) {
maxSumIndex = i;
}
}
for (int j = 0; j < numCols; ++j) {
int temp = matrix[minSumIndex][j];
matrix[minSumIndex][j] = matrix[maxSumIndex][j];
matrix[maxSumIndex][j] = temp;
}
std::cout << "Rows with min and max sums are swapped." << std::endl;
std::cout << "Updated matrix:" << std::endl;
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numCols; ++j) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
delete[] rowSums;
}
int main() {
int numRows, numCols;
std::cout << "Enter the number of rows: ";
std::cin >> numRows;
std::cout << "Enter the number of columns: ";
std::cin >> numCols;
int** matrix = new int*[numRows];
for (int i = 0; i < numRows; ++i) {
matrix[i] = new int[numCols];
}
std::cout << "Enter the elements of the matrix:" << std::endl;
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numCols; ++j) {
std::cin >> matrix[i][j];
}
}
findSumOfRows(matrix, numRows, numCols);
for (int i = 0; i < numRows; ++i) {
delete[] matrix[i];
}
delete[] matrix;
return 0;
}
