Question
Shift rows of matrix in cyclic order that is, Swap 1st row with 2nd row, 2nd row with 3rd and last row with 1st. Display the Original array and array after swapping.
Enter Number of rows:
4
Enter Number of columns:
4
Enter Elements in Array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Original Array:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Array After Cycling row :
13 14 15 16
1 2 3 4
5 6 7 8
9 10 11 12
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class CyclicMatrix
{
public static void main()
{
int[ ][ ] arr,newarr;
int row,col;
int i,j;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Number of rows:");
row=sc.nextInt();
System.out.println("Enter Number of columns:");
col=sc.nextInt();
arr=new int[row][col];
newarr=new int[row][col];
System.out.println("Enter Elements in Array:");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
arr[i][j]=sc.nextInt();
}
}
System.out.println("Original Array:");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
if(i==0)
{
newarr[i][j]=arr[row-1][j];
}
else
{
newarr[i][j]=arr[i-1][j];
}
}
}
System.out.println("Array After Cycling row :");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
System.out.print(newarr[i][j]+" ");
}
System.out.println();
}
}
}