Transpose

Lab Java Intermediate 20 points

Read an r×c matrix and print its transpose (c rows, r columns).

Input

r c, then r rows.

Output

c rows.

Example

Input

2 3
1 2 3
4 5 6

Output

1 4
2 5
3 6
Sample input available Sample output available
Editor
Java

Hints

The transpose's row j is the original's column j.

Solution explanation

Element (i, j) moves to (j, i).

Show solution
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int r = sc.nextInt(), c = sc.nextInt();
        int[][] m = new int[r][c];
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                m[i][j] = sc.nextInt();
            }
        }
        for (int j = 0; j < c; j++) {
            StringBuilder row = new StringBuilder();
            for (int i = 0; i < r; i++) {
                row.append(m[i][j]).append(i < r - 1 ? " " : "");
            }
            System.out.println(row);
        }
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD