Skip to content

Commit b2402d9

Browse files
Create rotate_by_90.cpp
1 parent fa77c96 commit b2402d9

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

2D Arrays/rotate_by_90.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include<bits/stdc++.h>
2+
#include <stdio.h>
3+
using namespace std;
4+
5+
int main()
6+
{
7+
int t; cin>>t;
8+
9+
while(t--)
10+
{
11+
int n;
12+
cin>>n;
13+
int matrix[n][n];
14+
15+
for(int i = 0; i < n; i++)
16+
{
17+
for(int j = 0; j < n; j++)
18+
{
19+
cin>>matrix[i][j];
20+
}
21+
}
22+
23+
//rotating the matrix by 90 , anticlockwise
24+
// the matrix will have floor(n/2) cycles
25+
for(int i=0; i<n/2; i++)
26+
{
27+
//parsing through each cycle and rotating
28+
for(int j=i; j< n-i-1; j++)
29+
{
30+
//stored current element in temporary variable temp
31+
int temp= matrix[i][j];
32+
33+
//shifted right element to top
34+
matrix[i][j]= matrix[j][n-i-1];
35+
36+
//shifted bottom element to right
37+
matrix[j][n-i-1]= matrix[n-1-i][n-1-j];
38+
39+
//shifted left element to bottom
40+
matrix[n-1-i][n-1-j] = matrix[n-1-j][i];
41+
42+
//assign temp to left
43+
matrix[n-1-j][i]= temp;
44+
}
45+
}
46+
47+
for(int i = 0; i < n; i++)
48+
for(int j=0; j<n; j++)
49+
cout<< matrix[i][j];
50+
cout<<endl;
51+
}
52+
return 0;
53+
}

0 commit comments

Comments
 (0)