Rotate matrix by 90 degrees In place C Program

Simple C program to rotate matrix by 90 degrees.





C Program:

/* Rotate matrix by 90 degrees */
#include<stdio.h>
 
void Swap(int *a,int *b)
{
 int temp=*a;
 *a=*b;
 *b=temp;
}
 
int main()
{
 int matrix[100][100];
 int i,j,m,n;
 printf("Enter rows and columns: ");
 scanf("%d%d",&m,&n);
 
 printf("Enter matrix elements: \n");
 for(i=0;i<m;i++)
 {
  for(j=0;j<n;j++)
  {
   scanf("%d",&matrix[i][j]);
  }
 }
 
 printf("Matrix is: \n");
 for(i=0;i<m;i++)
 {
  for(j=0;j<n;j++)
  {
   printf("%d  ",matrix[i][j]);
  }
  printf("%\n");
 }
 
 /* Transpose of a matrix */
 for(i=0;i<m;i++)
 {
  for(j=i;j<n;j++)
  {
   int temp=matrix[i][j];
   matrix[i][j]=matrix[j][i];
   matrix[j][i]=temp;
  }
 }
 
 Swap(&m,&n);
 /* Reverse every row */
 for(i=0;i<m;i++)
 {
  for(j=0;j<n/2;j++)
  {
   int temp=matrix[i][j];
   matrix[i][j]=matrix[i][n-1-j];
   matrix[i][n-1-j]=temp;
  }
 
 }
 printf("\n Matrix after rotation:\n");
 for(i=0;i<m;i++)
 {
  for(j=0;j<n;j++)
  {
   printf("%d  ",matrix[i][j]);
  }
  printf("\n");
 }
 
 return 0;
}

Please comment if you find anything wrong.

Popular posts from this blog