InterviewSolution
Saved Bookmarks
| 1. |
Write a program in Java to input an NxN matrix and display it row-wise and column-wise. |
|
Answer» Simply input the matrix. Now, display the matrix row-wise by starting from the first row and moving to the next elements within the same row. For displaying column-wise, start from the first column and keep moving in the same column to the next elements. This is shown below. Java Code to input and display 2-D Matrix import java.util.*;class Main { public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int N = scn.nextInt(); int[][] mat = new int[N][N]; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { mat[i][j] = scn.nextInt(); } } //Display Row wise for(int i=0;i<N;i++) { System.out.print("Row " + i + " : "); for(int j=0;j<N;j++) { System.out.print(mat[i][j] + " "); } System.out.println("\t"); } System.out.println(); //Display Col wise for(int j=0;j<N;j++) { System.out.print("Col " + j + " : "); for(int i=0;i<N;i++) { System.out.print(mat[i][j] + " "); } System.out.println("\t"); } } } Sample Output Input:3 1 2 3 4 5 6 7 8 9 Output: Row 0 : 1 2 3 Row 1 : 4 5 6 Row 2 : 7 8 9 Col 0 : 1 4 7 Col 1 : 2 5 8 Col 2 : 3 6 9
|
|