67 248
Assignments Done
99,3%
Successfully Done
In November 2018

Answer to Question #2647 in C++ for skymoon

Question #2647
Write a C++ program that reads numbers into a 2D array. The program gives the user an option to sort the array by row total or by column total and display the sorted array after sorting.
Expert's answer
#include <iostream>
#include <conio.h>
using namespace std;

// The 2D array of integers to sort
const int size = 4;
int arr[size][size];

// Printing the array
void print_array(int& ar[][size], const int rows, const int cols);

// Sorting the array by row total
void sort_by_rows(int ar[][size], const int rows, const int cols);


// Sorting the array by columns total
void sort_by_columns(int ar[][size], const int rows, const int cols);

int main()
{
// Reading the array
cout << "Enter the integer elements of the array, please (total 16)\n";
for (int i = 0; i < size; i++)
& for (int j = 0; j < size; j++)
& cin >> arr[i][j];
cout << "The array is: " << endl;
print_array(arr, size, size);

// Define the method of sorting (by row total or by column total)
cout << "\nSort by row total or column total? (r/c) ";
char answer;
do
{
& answer = getch();
}
while (!(answer == 'c' || answer == 'r'));
putch(answer);
cout << endl << endl;

if (answer == 'r')
{
& // Sorting array by rows
& cout << "\nThe array sorted by row total: \n";
& sort_by_rows(arr, size, size);
& print_array(arr, size, size);
}
else
{
& // Sorting array by rows
& cout << "\nThe array sorted by column total: \n";
& sort_by_columns(arr, size, size);
& print_array(arr, size, size);
}
cout << endl;

return 0;
}

// Printing the array
void print_array(int ar[][size], const int rows, const int cols)
{
for (int i = 0; i < rows; i++)
{
& for (int j = 0; j < cols; j++)
& cout << ar[i][j] << "\t";
& cout << endl;
}
}

// Sorting the array by row total
void sort_by_rows(int ar[][size], const int rows, const int cols)
{
for(int i = 0; i < rows; i++)
{
& for(int j = 0; j < cols; j++)
& {
& for(int k = cols - 1; k > j; k--)
& if(ar[i][k-1] > ar[i][k])
& {
& int temp = ar[i][k-1];
& ar[i][k-1] = ar[i][k];
& ar[i][k] = temp;
& }
& }
}
}

// Sorting the array by columns total
void sort_by_columns(int ar[][size], const int rows, const int cols)
{
for(int j = 0; j < cols; j++)
{
& for(int i = 0; i < rows; i++)
& {
& for(int k = rows - 1; k > i; k--)
& if(ar[k-1][j] > ar[k][j])
& {
& int temp = ar[k-1][j];
& ar[k-1][j] = ar[k][j];
& ar[k][j] = temp;
& }
& }
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions