Computer Science

Write a program in Java to enter natural numbers in a double dimensional array mxn (where m is the number of rows and n is the number of columns). Shift the elements of 4th column into the 1st column, the elements of 1st column into the 2nd column and so on. Display the new matrix.

111674
810918
981215
1415136
Sample Input
411167
188109
159812
6141513
Sample Output

Java

Java Arrays

15 Likes

Answer

import java.util.Scanner;

public class KboatSDAColShift
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number of rows (m): ");
        int m = in.nextInt();
        System.out.print("Enter number of columns (n): ");
        int n = in.nextInt();
        
        int arr[][] = new int[m][n];
        int newArr[][] = new int[m][n];
        
        System.out.println("Enter array elements");
        for (int i = 0; i < m; i++) {
            System.out.println("Enter Row "+ (i+1) + " :");
            for (int j = 0; j < n; j++) {
                arr[i][j] = in.nextInt();
            }
        }
        
        System.out.println("Input Array:");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
        
        for (int j = 0; j < n; j++) {
            int col = j + 1;
            if (col == n) {
                col = 0;
            }
            for (int i = 0; i < m; i++) {
                newArr[i][col] = arr[i][j]; 
            }
        }
        
        System.out.println("New Shifted Array:");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(newArr[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Output

Answered By

4 Likes


Related Questions