Programming lesson
Mastering 2D Arrays and Pointers in C++: A Menu-Driven Matrix Analyzer
Learn how to build a menu-driven C++ program that processes a 4x5 matrix using functions for totals, averages, row/column operations, and pointers. Includes real-world analogies and error checking.
Introduction: Why 2D Arrays and Pointers Matter in 2026
In today's data-driven world, from AI models processing pixel grids to gaming engines handling leaderboards, two-dimensional arrays and pointers are fundamental. This tutorial guides you through building a menu-driven matrix analyzer—similar to what you'd find in assignment #09 for Computer Science 1081. By the end, you'll confidently handle 2D arrays, function decomposition, and pointer parameters.
Setting Up the 4x5 Matrix
We'll start by declaring a 4x5 integer matrix and prompting the user for values. Use nested loops to fill each cell. Remember to validate input to avoid crashes—error checking is crucial for robust programs.
const int ROWS = 4;
const int COLS = 5;
int matrix[ROWS][COLS];
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
cout << "Enter value for [" << i << "][" << j << "]: ";
cin >> matrix[i][j];
// basic error check could go here
}
}Implementing getTotal and getAverage
The getTotal function sums all elements. Think of it like tallying total points across a gaming tournament's scoreboard. getAverage divides by total cells. Use double for precision.
int getTotal(int arr[][COLS], int rows) {
int total = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < COLS; j++)
total += arr[i][j];
return total;
}
double getAverage(int arr[][COLS], int rows) {
int total = getTotal(arr, rows);
return static_cast<double>(total) / (rows * COLS);
}Row and Column Totals: getRowTotal and getColumnTotal
These functions take an integer index. Validate the index before processing. For getRowTotal, sum across columns for that row. For getColumnTotal, sum down rows. This is like analyzing stats per player (row) or per round (column) in an esports match.
int getRowTotal(int arr[][COLS], int row) {
int total = 0;
for (int j = 0; j < COLS; j++)
total += arr[row][j];
return total;
}
int getColumnTotal(int arr[][COLS], int col) {
int total = 0;
for (int i = 0; i < ROWS; i++)
total += arr[i][col];
return total;
}Highest and Lowest in a Row
Scan the row to find max and min. getHighestInRow and getLowestInRow are straightforward. Imagine finding the top and bottom scores in a leaderboard row.
int getHighestInRow(int arr[][COLS], int row) {
int highest = arr[row][0];
for (int j = 1; j < COLS; j++)
if (arr[row][j] > highest)
highest = arr[row][j];
return highest;
}
int getLowestInRow(int arr[][COLS], int row) {
int lowest = arr[row][0];
for (int j = 1; j < COLS; j++)
if (arr[row][j] < lowest)
lowest = arr[row][j];
return lowest;
}Building the Menu Loop
Use a do-while loop that displays options and calls the appropriate function based on user choice. Include error handling for invalid menu selections and row/column indices.
int choice;
do {
cout << "\nMenu:\n";
cout << "1. Total of all cells\n";
cout << "2. Average of all cells\n";
cout << "3. Total of a row\n";
cout << "4. Total of a column\n";
cout << "5. Highest in a row\n";
cout << "6. Lowest in a row\n";
cout << "7. Exit\n";
cout << "Enter choice: ";
cin >> choice;
switch(choice) {
case 1: cout << "Total: " << getTotal(matrix, ROWS); break;
case 2: cout << "Average: " << getAverage(matrix, ROWS); break;
case 3: {
int r;
cout << "Enter row (0-3): ";
cin >> r;
if (r >= 0 && r < ROWS)
cout << "Row total: " << getRowTotal(matrix, r);
else
cout << "Invalid row!";
break;
}
case 4: {
int c;
cout << "Enter column (0-4): ";
cin >> c;
if (c >= 0 && c < COLS)
cout << "Column total: " << getColumnTotal(matrix, c);
else
cout << "Invalid column!";
break;
}
case 5: {
int r;
cout << "Enter row (0-3): ";
cin >> r;
if (r >= 0 && r < ROWS)
cout << "Highest in row: " << getHighestInRow(matrix, r);
else
cout << "Invalid row!";
break;
}
case 6: {
int r;
cout << "Enter row (0-3): ";
cin >> r;
if (r >= 0 && r < ROWS)
cout << "Lowest in row: " << getLowestInRow(matrix, r);
else
cout << "Invalid row!";
break;
}
case 7: cout << "Exiting..."; break;
default: cout << "Invalid choice!";
}
} while (choice != 7);Pointer Practice: Doubling Values
Now for the second program: use three integer variables and three functions. getValues gets input via pass-by-reference (pointers). doubleValues doubles each using pointers. displayValues shows them (pass-by-value). This reinforces when to use pointers.
void getValues(int *a, int *b, int *c) {
cout << "Enter an integer: ";
cin >> *a;
cout << "Enter an integer: ";
cin >> *b;
cout << "Enter an integer: ";
cin >> *c;
}
void doubleValues(int *a, int *b, int *c) {
*a *= 2;
*b *= 2;
*c *= 2;
}
void displayValues(int a, int b, int c) {
cout << "The values doubled are: " << a << ", " << b << ", " << c << endl;
}
int main() {
int x, y, z;
getValues(&x, &y, &z);
doubleValues(&x, &y, &z);
displayValues(x, y, z);
return 0;
}Error Checking and Best Practices
Always validate user input: menu choices must be integers within range, row/column indices must be within bounds. Use loops to reprompt on invalid input. This prevents crashes and improves user experience—crucial for any real-world application like a banking app or game stats tracker.
Conclusion
You've built a complete matrix analyzer using 2D arrays and pointer functions. These skills transfer to many areas: from AI data preprocessing to gaming leaderboards. Practice by extending the menu or adding file I/O. Happy coding!