Write a C program to rotate the given matrix left by n places.
#include <stdio.h>
#define ROW 10
#define COL 10
int main() {
int i, j, k, n, rotate, tmp[ROW], mat[ROW][COL];
/* get the order of the matrix from the user */
printf("Enter the order of the matrix:");
scanf("%d", &n);
/* get the input matrix from the user */
printf("Enter your matrix entries:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &mat[i][j]);
}
}
/* get the input to rotate the given matrix by left */
printf("Rotate the matrix left by ");
scanf("%d", &rotate);
/* rotate the given matrix by given n places */
for (i = 0; i < rotate; i++) {
for (j = 0; j < n; j++) {
tmp[j] = mat[j][0];
}
for (j = 1; j <= n - 1; j++) {
for (k = 0; k < n; k++) {
mat[k][j - 1] = mat[k][j];
}
}
#define ROW 10
#define COL 10
int main() {
int i, j, k, n, rotate, tmp[ROW], mat[ROW][COL];
/* get the order of the matrix from the user */
printf("Enter the order of the matrix:");
scanf("%d", &n);
/* get the input matrix from the user */
printf("Enter your matrix entries:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &mat[i][j]);
}
}
/* get the input to rotate the given matrix by left */
printf("Rotate the matrix left by ");
scanf("%d", &rotate);
/* rotate the given matrix by given n places */
for (i = 0; i < rotate; i++) {
for (j = 0; j < n; j++) {
tmp[j] = mat[j][0];
}
for (j = 1; j <= n - 1; j++) {
for (k = 0; k < n; k++) {
mat[k][j - 1] = mat[k][j];
}
}
for (j = 0; j < n; j++) {
mat[j][n - 1] = tmp[j];
}
}
/* print the result */
printf("Resultant Matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
printf("\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the order of the matrix:3
Enter your matrix entries:
10 20 30
40 50 60
70 80 90
Rotate the matrix left by 2
Resultant Matrix:
30 10 20
60 40 50
90 70 80
Enter the order of the matrix:3
Enter your matrix entries:
10 20 30
40 50 60
70 80 90
Rotate the matrix left by 2
Resultant Matrix:
30 10 20
60 40 50
90 70 80
No comments:
Post a Comment