Given a matrix the task is to cyclic shift the elements of each row upwards by one place.
Example:
| 3 | 1 |
| 9 | 2 |
| 4 | 8 |
→
| 9 | 2 |
| 4 | 8 |
| 3 | 1 |
Java
import java.util.*;
public class ShiftRow
{
int ar[][];int row;int col;
ShiftRow(int m,int n)
{
row=m;
col=n;
ar=new int[m][n];
}
public void getElements()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter matrix elements:-");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
ar[i][j]=sc.nextInt();
}
}
}
public void doShift(ShiftRow A)
{
for(int i=0;i<col;i++)
{
for(int j=0;j<row-1;j++)
{
ar[j][i]=A.ar[j+1][i];
}
ar[row-1][i]=A.ar[0][i];
}
}
public void displayMatrix()
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
System.out.print(ar[i][j]+"\t");
}
System.out.println();
}
}
public static void main(String args[])
{
int m=0,n=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter no.of rows: ");
m=sc.nextInt();
System.out.print("Enter no.of columns: ");
n=sc.nextInt();
ShiftRow ob1=new ShiftRow(m,n);
ShiftRow ob2=new ShiftRow(m,n);
ob1.getElements();
System.out.println("Original Matrix:-");
ob1.displayMatrix();
ob2.doShift(ob1);
System.out.println("New Matrix:-");
ob2.displayMatrix();
}
}Java