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
|
#include "stdafx.h"
#include "targetver.h"
#include <iostream>
#include <iomanip>
using namespace std;
const int ROWS = 5;
const int COLS = 5;
void displayMenu();
int getInput();
void displayArray(const int [][COLS], int);
void multiArray(int [][COLS], int);
void swapArray(int [][COLS], int);
void sum(int [][COLS], int);
void displayExit();
void displayError();
int main() {
int myArray[ROWS][COLS] = {
{1,2,3,4,5},
{-20,-40,-60,-80,-100},
{3,3,3,3,3},
{5,7,9,11,13},
{-15,-25,-35,-45,-55}
};
int choice = 0;
do {
displayMenu();
choice = getInput();
switch (choice)
{
case 1:
displayArray(myArray, ROWS);
break;
case 2:
multiArray(myArray, ROWS);
break;
case 3:
swapArray(myArray, ROWS);
break;
case 4:
sum(myArray, ROWS);
break;
case 5:
displayExit();
break;
default:
displayError();
break;
}
} while (choice != 5);
}
void displayMenu() {
cout << "\t\tMain Menu" << endl << endl;
cout << "1. Display array: " << endl;
cout << "2. Multiply array by 3: " << endl;
cout << "3. Swap row 2 and row 3: " << endl;
cout << "4. Display sum of all elements: " << endl;
cout << "5. Exit" << endl << endl;
}
int getInput() { // added getInput function to gather the input from the user
cout << "Input values 1 through 4, or 5 to exit program: ";
int choice;
if (!(cin >> choice)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
choice = 0;
}
cout << endl;
return choice;
}
void displayArray(const int myArray[][COLS], int rows) {
cout << "Current Array: " << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < COLS; j++) {
cout << setw(5) << right << myArray[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void multiArray(int myArray[][COLS], int rows) {
for (int i = 0; i < rows; i++) {
for (int &val : myArray[row]) {
val *= 3;
}
}
cout << "Array multiplied by 3" << endl << endl;
}
void swapArray(int myArray[][COLS], int rows) {
}
void sum(int myArray[][COLS], int rows) {
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < COLS; j++) {
sum += myArray[i][j];
}
}
cout << "The sum of all values in the array is: " << sum << endl << endl;
}
void displayExit() {
cout << "The Program will now end" << endl;
}
void displayError() {
cout << "Sorry, that is not a valid choice." << endl;
}
|