Question #24630

QUESTION: "write a C++ program for the matrix of integers to swap the first row and row
containing the largest element in absolute value".
matrix.

Expert's answer

#include <cmath>

#include <ctime>

#include <cstdlib>

#include <iomanip>

#include <iostream>

#include <conio.h>

using namespace std;

const int MATRIX_SIZE = 5;

void print_matrix(int (&matrix)[MATRIX_SIZE][MATRIX_SIZE])

{

for (int x = 0; x < MATRIX_SIZE; x++)

{

for (int y = 0; y < MATRIX_SIZE; y++)

cout << setw(4) << matrix[x][y];

cout << endl;

}

cout << endl;

}

int find_max_element_row(int (&matrix)[MATRIX_SIZE][MATRIX_SIZE])

{

int row = 0;

int maxElement = -1;

for (int x = 0; x < MATRIX_SIZE; x++)

for (int y = 0; y < MATRIX_SIZE; y++)

if (abs(matrix[x][y]) > maxElement)

{

maxElement = abs(matrix[x][y]);

row = x;

}

return row;

}

void swap_rows(int (&matrix)[MATRIX_SIZE][MATRIX_SIZE], int rowA, int rowB)

{

int tmp;

for (int y = 0; y < MATRIX_SIZE; y++)

{

tmp = matrix[rowA][y];

matrix[rowA][y] = matrix[rowB][y];

matrix[rowB][y] = tmp;

}

}

int main()

{

int matrix[5][5];

srand(time(NULL));

for (int x = 0; x < MATRIX_SIZE; x++)

for (int y = 0; y < MATRIX_SIZE; y++)

matrix[x][y] = rand() % 30;

cout << "The initial matrix:" << endl;

print_matrix(matrix);

swap_rows(matrix, find_max_element_row(matrix), 0);

cout << "The resulting matrix:" << endl;

print_matrix(matrix);

_getch();

return 0;

}

#include <ctime>

#include <cstdlib>

#include <iomanip>

#include <iostream>

#include <conio.h>

using namespace std;

const int MATRIX_SIZE = 5;

void print_matrix(int (&matrix)[MATRIX_SIZE][MATRIX_SIZE])

{

for (int x = 0; x < MATRIX_SIZE; x++)

{

for (int y = 0; y < MATRIX_SIZE; y++)

cout << setw(4) << matrix[x][y];

cout << endl;

}

cout << endl;

}

int find_max_element_row(int (&matrix)[MATRIX_SIZE][MATRIX_SIZE])

{

int row = 0;

int maxElement = -1;

for (int x = 0; x < MATRIX_SIZE; x++)

for (int y = 0; y < MATRIX_SIZE; y++)

if (abs(matrix[x][y]) > maxElement)

{

maxElement = abs(matrix[x][y]);

row = x;

}

return row;

}

void swap_rows(int (&matrix)[MATRIX_SIZE][MATRIX_SIZE], int rowA, int rowB)

{

int tmp;

for (int y = 0; y < MATRIX_SIZE; y++)

{

tmp = matrix[rowA][y];

matrix[rowA][y] = matrix[rowB][y];

matrix[rowB][y] = tmp;

}

}

int main()

{

int matrix[5][5];

srand(time(NULL));

for (int x = 0; x < MATRIX_SIZE; x++)

for (int y = 0; y < MATRIX_SIZE; y++)

matrix[x][y] = rand() % 30;

cout << "The initial matrix:" << endl;

print_matrix(matrix);

swap_rows(matrix, find_max_element_row(matrix), 0);

cout << "The resulting matrix:" << endl;

print_matrix(matrix);

_getch();

return 0;

}

## Comments

## Leave a comment