Given a matrix the task is to cyclic shift the elements of each column left by one place.
Example:
| 3 | 1 | 4 |
| 9 | 2 | 8 |
→
| 1 | 4 | 3 |
| 2 | 8 | 9 |
Java
import java.util.*;
public class ShiftColumn
{
int ar[][];int row;int col;
ShiftColumn(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(ShiftColumn A)
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col-1;j++)
{
ar[i][j]=A.ar[i][j+1];
}
ar[i][col-1]=A.ar[i][0];
}
}
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();
ShiftColumn ob1=new ShiftColumn(m,n);
ShiftColumn ob2=new ShiftColumn(m,n);
ob1.getElements();
System.out.println("Original Matrix:-");
ob1.displayMatrix();
ob2.doShift(ob1);
System.out.println("New Matrix:-");
ob2.displayMatrix();
}
}Java