34.1k views
2 votes
Create a 4×4 matrix (2 dimension) and traverse it row-wise and column-wise. Display the result on screen.

Example:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

Output 1 (row-wise): 1 2 3 4 5 6 7 8 9 10 11 12

13 14 15 16

Output 2 (column-wise): 1 5 9 13 2 6 10 14 3 7

11 15 4 8 12 16

User Vivek
by
7.4k points

1 Answer

4 votes

Final answer:

To create a 4x4 matrix in Python and traverse it row-wise and column-wise, you can use nested lists and for loops. The row-wise traversal can be done by iterating over each row in the matrix and printing each element. The column-wise traversal can be done by using the zip() function and iterating over each column.

Step-by-step explanation:

To create a 4×4 matrix, you can use nested lists in Python. Here is an example:

matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

To traverse the matrix row-wise, you can use a nested for loop:

for row in matrix:
for element in row:
print(element, end=' ')
print()

To traverse the matrix column-wise, you can use zip() function along with the * operator:

columns = zip(*matrix)
for column in columns:
for element in column:
print(element, end=' ')
print()

User Johannes Merz
by
8.1k points