1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
|
#include <iostream>
#include <stdlib.h>
using namespace std;
void printMatrix(int** matrix, int n, int m)
{
cout << "Printed matrix: " << endl;
for(int i=0; i<n; i++)
{
for (int j=0; j<m; j++)
{
cout << matrix[i][j] << "\t";
}
cout << endl;
}
};
void getSum(int** matrix, int n, int m)
{
int sum=0;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
sum += matrix[i][j];
}
}
cout << "The sum of all numbers is: " << sum << endl;
};
void printUpper(int** matrix, int n, int m)
{
if(n != m)
{
cout << "The matrix is not square.\n";
return;
}
cout << "The upper half of the array: \n";
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(j<i)
{
cout << "\t";
continue;
}
cout << matrix[i][j] << "\t";
}
cout << endl;
}
}
void printMiddleRow(int** matrix, int n, int m)
{
if(n%2==0)
{
cout << "Error! The number of rows is even. Cannnot print the middle.\n";
return;
}
cout << "The middle row: " << endl;
int mid = n/2;
for(int i=0; i<m; i++)
{
cout << matrix[mid][i] << "\t";
}
cout << endl;
};
void printMiddleCol(int** matrix, int n, int m)
{
if(m%2==0)
{
cout << "Error! The number of columns is even. Cannot print the middle.\n";
return;
}
cout << "The middle column: \n";
int mid = m/2;
for(int i=0; i<m; i++)
{
cout << matrix[i][mid] << "\t";
}
cout << endl;
};
int main(int argc, char* argv[])
{
if(argc<0)//checks to make sure user inputs dimensions of array
cout << "Error! More command line arguments are required.\n";
int n = atoi(argv[1]);
int m = atoi(argv[2]);
int** matrix = new int*[n];
for(int i=0; i<n; i++)
{
matrix[i] = new int[m];
}
int cur = 3;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
matrix[i][j] = atoi(argv[cur]);
cur++;
}
}
cout << "Please choose from the following options: \n";
cout << "1. Print the matrix.\n";
cout << "2. Sum all of the elements.\n";
cout << "3. Show the upper half.\n";
cout << "4. Show the middle row.\n";
cout << "5. Show the middle column.\n";
int choice;
cout << "Enter selection: ";
cin >> choice;
switch(choice)
{
case(1):
printMatrix(matrix, n, m);
break;
case(2):
getSum(matrix, n, m);
break;
case(3):
printUpper(matrix, n, m);
break;
case(4):
printMiddleRow(matrix, n, m);
break;
case(5):
printMiddleCol(matrix, n, m);
break;
default:
cout << "Invalid selection. Goodbye.\n";
}
return 0;
}
|