Rotate the matrix right by K times | CPP program to rotate a matrix right by k times ; size of matrix ; function to rotate matrix by k times ; temporary array of size M ; within the size of matrix ; copy first M - k elements to temporary array ; copy the elements from k to end to starting ; copy elements from temporary array to end ; function to display the matrix ; Driver 's code ; rotate matrix by k ; display rotated matrix
#include <iostream> NEW_LINE #define M  3 NEW_LINE #define N  3 NEW_LINE using namespace std ; void rotateMatrix ( int matrix [ ] [ M ] , int k ) { int temp [ M ] ; k = k % M ; for ( int i = 0 ; i < N ; i ++ ) { for ( int t = 0 ; t < M - k ; t ++ ) temp [ t ] = matrix [ i ] [ t ] ; for ( int j = M - k ; j < M ; j ++ ) matrix [ i ] [ j - M + k ] = matrix [ i ] [ j ] ; for ( int j = k ; j < M ; j ++ ) matrix [ i ] [ j ] = temp [ j - k ] ; } } void displayMatrix ( int matrix [ ] [ M ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) cout << matrix [ i ] [ j ] << " ▁ " ; cout << endl ; } } int main ( ) { int matrix [ N ] [ M ] = { { 12 , 23 , 34 } , { 45 , 56 , 67 } , { 78 , 89 , 91 } } ; int k = 2 ; rotateMatrix ( matrix , k ) ; displayMatrix ( matrix ) ; return 0 ; }