Write a C program to rotate the given matrix right by n places.
#include <stdio.h>
#define ROW 10
#define COL 10
int main() {
int i, j, k, n, rotate, temp[ROW], matrix[ROW][COL];
/* get the order of the matrix from the user */
printf("Enter the order of the matrix:");
scanf("%d", &n);
/* get the entries for the input matrix */
printf("Enter your matrix entries:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
/* get the input to rotate the input matrix */
printf("Rotate the matrix right by ");
scanf("%d", &rotate);
/* rotate the given matrix right by "rotate" places */
for (i = 0; i < rotate; i++) {
for (j = 0; j < n; j++) {
temp[j] = matrix[j][n-1];
}
for (j = n - 1; j >= 1; j--) {
for (k = 0; k < n; k++) {
matrix[k][j] = matrix[k][j - 1];
}
}
#define ROW 10
#define COL 10
int main() {
int i, j, k, n, rotate, temp[ROW], matrix[ROW][COL];
/* get the order of the matrix from the user */
printf("Enter the order of the matrix:");
scanf("%d", &n);
/* get the entries for the input matrix */
printf("Enter your matrix entries:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
/* get the input to rotate the input matrix */
printf("Rotate the matrix right by ");
scanf("%d", &rotate);
/* rotate the given matrix right by "rotate" places */
for (i = 0; i < rotate; i++) {
for (j = 0; j < n; j++) {
temp[j] = matrix[j][n-1];
}
for (j = n - 1; j >= 1; j--) {
for (k = 0; k < n; k++) {
matrix[k][j] = matrix[k][j - 1];
}
}
for (j = 0; j < n; j++) {
matrix[j][0] = temp[j];
}
}
/* print the resultant matrix */
printf("Resultant matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
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 right by 2
Resultant matrix:
20 30 10
50 60 40
80 90 70
Enter the order of the matrix:3
Enter your matrix entries:
10 20 30
40 50 60
70 80 90
Rotate the matrix right by 2
Resultant matrix:
20 30 10
50 60 40
80 90 70
No comments:
Post a Comment