[CS]
WAP to accept m×n matric, shift each row 1 step downward.
Sample Input:-
Enter no. of rows and columns
4
5
Enter elements of 3×4 matric
1 2 3 4 5
2 4 6 8 0
3 6 9 0 3
4 8 0 4 8
Required Output:-
4 8 0 4 8
1 2 3 4 5
2 4 6 8 0
3 6 9 0 3
Answers
Approach 1:
In this approach, we will copy the last row of the matrix and store the values in another array.
Consider a matrix A -
Here, we will store elements of the last row into another array -
Now we will shift elements down.
Now, we will add the elements of b to the first row of matrix A.
So, the elements are shifted down. Here comes the code.
import java.util.*;
public class MatrixRowShiftUsingArray{
public static void main(String s[]){
Scanner sc=new Scanner(System.in);
int rows,cols,i,j;
System.out.print("How many rows: ");
rows=sc.nextInt();
System.out.print("How many cols: ");
cols=sc.nextInt();
int a[][]=new int[rows][cols];
int b[]=new int[cols];
System.out.println("Enter elements...");
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
System.out.printf("a[%d][%d] >> ",i,j);
a[i][j]=sc.nextInt();
}
}
System.out.println("\nGiven Matrix:");
displayMatrix(a);
// Modification starts.
for(i=rows-1,j=0;j<cols;j++)
b[j]=a[i][j];
for(i=rows-2;i>=0;i--){
for(j=0;j<cols;j++){
a[i+1][j]=a[i][j];
}
}
for(j=0;j<cols;j++){
a[0][j]=b[j];
}
System.out.println("\nMatrix After Modification:");
displayMatrix(a);
}
static void displayMatrix(int a[][]){
for(int x[]:a){
for(int y:x)
System.out.print(y+" ");
System.out.println();
}
}
}
Note: The displayMatrix(a[][]) function is created to avoid repetition of code.
Approach 2:
Here, only 1 matrix is needed for the modification.
Consider the 3 x 4 matrix A -
Here, we will swap the first row with 2nd, 3rd and 4th row.
After first swap (1st with second),
After second swap (1st with third),
After third swap (1st with fourth),
Hence, our matrix is modified. Here comes the code for this.
import java.util.*;
public class MatrixRowShiftPart2{
public static void main(String s[]){
Scanner sc=new Scanner(System.in);
int rows,cols,i,j,t=1,y;
System.out.print("How many rows: ");
rows=sc.nextInt();
System.out.print("How many cols: ");
cols=sc.nextInt();
int a[][]=new int[rows][cols];
System.out.println("Enter array elements...");
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
System.out.printf("a[%d][%d] >> ",i,j);
a[i][j]=sc.nextInt();
}
}
System.out.println("\nGiven Matrix: ");
displayMatrix(a);
for(i=0;i<rows-1;i++,t++){
for(j=0;j<cols;j++){
y=a[0][j];
a[0][j]=a[t][j];
a[t][j]=y;
}
}
System.out.println("\nModified Matrix:");
displayMatrix(a);
}
static void displayMatrix(int a[][]){
for(int x[]:a){
for(int y:x)
System.out.print(y+" ");
System.out.println();
}
}
}
See the attachment for output.