2D Array Practical Practice Questions
1. Matrix Transpose
Write a program to find the transpose of a 2D array.
The transpose of a matrix is obtained by swapping rows and columns.
Example:
Input:
Matrix:
123
456
789
Output:
Transpose:
147
258
369
2. Sum of Elements
Write a program to calculate the sum of all elements in a 2D array.
Example:
Input:
Matrix:
123
456
789
Output:
Sum: 45
3. Row-wise and Column-wise Sum
Write a program to calculate and display:
- The sum of each row in a 2D array.
- The sum of each column in a 2D array.
Example:
Input:
Matrix:
123
456
789
Output:
Row-wise Sum:
Row 1: 6
Row 2: 15
Row 3: 24
Column-wise Sum:
Column 1: 12
Column 2: 15
Column 3: 18
4. Matrix Multiplication
Write a program to multiply two matrices. Ensure the number of columns in the first matrix equals
the number of rows in the second matrix.
Example:
Input:
Matrix A:
12
34
Matrix B:
56
78
Output:
Resultant Matrix:
19 22
43 50
5. Identity Matrix Check
Write a program to check whether a given square matrix is an identity matrix.
An identity matrix has 1s on the main diagonal and 0s elsewhere.
Example:
Input:
Matrix:
100
010
001
Output:
The matrix is an identity matrix.
6. Diagonal Sum
Write a program to find the sum of the primary and secondary diagonals of a square matrix.
Example:
Input:
Matrix:
123
456
789
Output:
Primary Diagonal Sum: 15 (1 + 5 + 9)
Secondary Diagonal Sum: 15 (3 + 5 + 7)
7. Spiral Traversal
Write a program to print the elements of a 2D array in a spiral order.
Example:
Input:
Matrix:
1 2 3
4 5 6
7 8 9
Output:
Spiral Traversal: 1 2 3 6 9 8 7 4 5