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
|
// MOD: now using typedef, packaged while/if from main() into a now overloaded
// showArray function.
#include <iostream>
#include <iomanip>
using namespace std;
const int ARRAY_ROW_SIZE = 6; // 6 rows
const int ARRAY_COL_SIZE = 2; // 2 columns each
typedef const int Array[ARRAY_ROW_SIZE][ARRAY_COL_SIZE];
// function prototype now overloaded, it prints AND processes user choice
void showArray(Array, int); // prints array to screen
void showArray(Array, int, int); // processes user choice
int main()
{
int arrayX[ARRAY_ROW_SIZE][ARRAY_COL_SIZE] = {{1,38}, {2,42}, {3,66},
{4,33}, {5,66}, {6,55}};
int choice = 0; // user input choice
showArray(arrayX, ARRAY_ROW_SIZE);
cout << endl;
cout << "Pick one of the " << ARRAY_ROW_SIZE << " elements: ";
cin >> choice;
cout << endl;
showArray(arrayX, ARRAY_ROW_SIZE, choice);
return 0;
}
void showArray(Array arrayX, int numRows)
{
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < ARRAY_COL_SIZE; col++)
{
cout << setw(1) << arrayX[row][col] << " ";
}
cout << endl;
}
}
void showArray(Array arrayX, int numRows, int choice)
{
char repeat = 'y'; // while loop sentinel
while (repeat == 'y') // only continue while loop if answer is 'y'
{
// set boundry for array, no less than 1 to no more then array size
if (choice > 0 && choice <= ARRAY_ROW_SIZE)
{
// use choice-1 to match the screen printed list with elements starting at 1, not 0
cout << "Element " << choice << " contains the value " << arrayX[choice-1][1]
<< "." << endl;
}
else
{
// issue error if number is 0 or less, and greater than array size
cout << "ERROR! You can only pick a number from the " << ARRAY_ROW_SIZE
<< " elements." << endl;
} // end if choice check
// while loop control
cout << endl << "Repeat? (y or n): ";
cin >> repeat;
if (repeat == 'y')
{
// repeat user input within the while loop
cout << endl;
cout << "Pick which number you want to see: ";
cin >> choice;
cout << endl;
} // end if sentinel check
} // end while loop
}
|