Answer :
Answer:
import java.util.Scanner;
public class ShiftNumbers {
public static void movearr(int[][] arr, int move) {
for (int row = 0; row < arr.length; row++) {
int lengthOfRow = arr[row].length;
move = move % lengthOfRow;
int[] tmp = new int[move];
for (int i = 0; i < move; i++) {
tmp[i] = arr[row][i];
}
for (int col = 0; col < lengthOfRow - move; col++) {
arr[row][col] = arr[row][col + move];
}
for (int i = 0; i < move; i++) {
arr[row][i + (lengthOfRow - move)] = tmp[i];
}
}
}
public static void main(String []args){
System.out.println("Hello World");
int M=5;
int[][] arr1 = new int[M][M];
Scanner in=new Scanner(System.in);
System.out.println("Enter the 2 D arr elements");
for(int i=0;i<M;i++){
for(int j=0;j<M;j++){
arr1[i][j]=in.nextInt();
}
}
movearr(arr1, 1);
for (int[] row : arr1) {
for (int col : row) {
System.out.print(col);
}
System.out.println();
}
}
}
Explanation:
- Inside the ShiftNumbers class, use a for loop which runs within bounds of the arr ay.
- Inside the main method, run a nested for loop to take 2D array as an input from user.
- Clone the elements that will fall off , move as usual and then clone the fall off elements again.
- Call the movearr method and then display the results.