Shift a Matrix up by one row.
import java.util.*;;
class Shift {
int[][] mat;
int m, n;
Shift(int mm, int nn) {
m = mm;
n = nn;
mat = new int[m][n];
}
void input() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Matrix of " + m + " x " + n + " :");
for (int x = 0; x < m; x++)
for (int y = 0; y < n; y++)
mat[x][y] = sc.nextInt();
}
void cyclic(Shift A) {
int[][] mt = new int[m][n];
for (int x = 0; x < m; x++)
for (int y = 0; y < n; y++)
mt[(x - 1) % (m + 1)][y] = A.mat[x][y];
mat = mt;
}
void display() {
System.out.println("Shifted Arary :-");
for (int x = 0; x < m; x++) {
for (int y = 0; y < n; y++)
System.out.print(mat[x][y] + "\t");
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter m,n for Matrix: ");
Shift a = new Shift(sc.nextInt(), sc.nextInt());
a.input();
a.cyclic(a);
a.display();
sc.close();
}
}
| Name | Type | Uses |
|---|---|---|
| global | ||
| mat | int[][] | the matrix to be shifted by one row |
| m, n | int | dimensions of the matrix |
| void input() | ||
| sc | Scanner | object to take user input |
| x, y | int | counter variables used to enter value into the matrix |
| void cyclic() | ||
| mt | int[][] | the matrix to store the shifted matrix |
| x, y | int | counter variables to iterate over the matrix |
| void display() | ||
| x, y | int | counter variables to iterate over the matrix to print it |
| void main() | ||
| sc | Scanner | object to take user input |
| a | Shift | object to call the methods of the class |