# How to rotate a matrix of size n*n to 90-degree k times using C#?

The entire matrix needs to be rotated k number of times. In a matrix there is a total of n/2 squares in n*n matrix and we can process each square one at a time using nested loop. In each square, elements are moving in a cycle of 4 elements then we swap the elements involved in an anticlockwise direction for each cycle.

Element at position (n-1-j,i) will go to position(i,j)

Element at position (i,j) will go to position(j,n-1-i)

Element at position (j,n-1-i) will go to position(n-1-i,n-1-j)

Element at position (n-1-i,n-1-j) will go to position(n-1-j,i)

## Example

Live Demo

using System;
using System.Text;
namespace ConsoleApplication{
public class Matrix{
public void RotateMatrixByKTimes(int[,] matrix, int numberOftimes){
int n = matrix.GetLength(0);
for (int k = 0; k < numberOftimes; k++){
for (int i = 0; i < n / 2; i++){
for (int j = i; j < n - i - 1; j++){
int top = matrix[i, j];
//MOve left to top
matrix[i, j] = matrix[n - 1 - j, i];
//Move bottom to left
matrix[n - 1 - j, i] = matrix[n - i - 1, n - 1 - j];
//Move right to bottom
matrix[n - i - 1, n - 1 - j] = matrix[j, n - i - 1];
//Move top to right
matrix[j, n - i - 1] = top;
}
}
}
for (int i = 0; i < n; i++){
StringBuilder s = new StringBuilder();
for (int j = 0; j < n; j++){
s.Append(matrix[i, j] + " ");
}
Console.WriteLine(s);
s = null;
}
}
}
class Program{
static void Main(string[] args){
Matrix m = new Matrix();
int[,] matrix = { { 5, 1, 9, 11 }, { 2, 4, 8, 10 }, { 13, 3, 6, 7 }, { 15, 14, 12, 16 } };
m.RotateMatrixByKTimes(matrix, 2);
}
}
}

## Output

16 12 14 15
7   6  3 13
10  8  4 2
11  9  1 5