Menu Driven C++ Programs for 2D Arrays
Options:
- Input elements into the matrix of size m×n.
- Display elements of the matrix of size m×n.
- Sum of all elements of the matrix.
- Row-wise sum of the matrix.
- Column-wise sum of the matrix.
- Transpose of the matrix B of size n×m.
Answer:
void inputMatrix(int A[][MAX], int m, int n) { cout << "Enter elements:\n"; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) cin >> A[i][j]; } void displayMatrix(int A[][MAX], int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << A[i][j] << " "; cout << endl; } } int sumMatrix(int A[][MAX], int m, int n) { int sum = 0; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) sum += A[i][j]; return sum; }
Write user-defined functions for:
- Left diagonal sum
- Right diagonal sum
Answer:
int leftDiagonalSum(int A[][MAX], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += A[i][i]; return sum; } int rightDiagonalSum(int A[][MAX], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += A[i][n - i - 1]; return sum; }
Answer:
void multiplyRowElements(int A[4][6]) { for (int i = 0; i < 4; i++) { int product = 1; for (int j = 0; j < 6; j++) product *= A[i][j]; cout << "Row " << i + 1 << " product: " << product << endl; } }
Given a square matrix, display only the upper half (above and including the diagonal).
Answer:
void upperHalf(int A[][MAX], int N) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (j >= i) cout << A[i][j] << " "; else cout << " "; } cout << endl; } }
For a square matrix with odd dimensions (e.g., 3×3, 5×5), display:
- Middle row
- Middle column
Answer:
void displayMiddle(int A[][MAX], int N) { int middle = N / 2; cout << "Middle Row: "; for (int i = 0; i < N; i++) cout << A[middle][i] << " "; cout << "\nMiddle Column: "; for (int i = 0; i < N; i++) cout << A[i][middle] << " "; cout << endl; }
Answer:
void addMatrices(int A[][MAX], int B[][MAX], int C[][MAX], int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] + B[i][j]; } } cout << "Sum of matrices:\n"; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << C[i][j] << " "; } cout << endl; } }
Answer:
void multiplyMatrices(int A[][MAX], int B[][MAX], int C[][MAX], int N, int L, int M) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { C[i][j] = 0; for (int k = 0; k < L; k++) { C[i][j] += A[i][k] * B[k][j]; } } } cout << "Product of matrices:\n"; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << C[i][j] << " "; } cout << endl; } }