To rotate the matrix elements using c

To rotate the matrix elements using c

Question:

Write a c program to rotate the matrix elements for any length of matrix.

Logic:

  • Get the array elements from the user.
  • Then pick the second row first element.
  • And swap all elements in boundary sequentially to make rotation.
  • Then repeat the process for all other elements.
  • When we goes to middle of the matrix shows no rotation is left.
  • Al last we get rotated matrix.

Program:

#include<stdio.h>
void main()
{
	int a[20][20],r,c,i,j,cr,pr,m=0,n=0,x,y;
	clrscr();
	printf("enter the row size:");
	scanf("%d",&r);
	printf("enter the column size:");
	scanf("%d",&c);
	x=r;y=c;
	printf("enter the elements:");
	for(i=0;i<r;i++)
	{
		for(j=0;j<c;j++)
		{
			scanf("%d",&a[i][j]);
		}
	}
	printf("Before rotation:\n");
	for(i=0;i<x;i++)
	{
		for(j=0;j<y;j++)
		{
			printf("%d ",a[i][j]);
		}
		printf("\n");
	}
	while(r>m&&c>n)
	{
		if(m+1==r||n+1==c)//exits when no other rotation is available
		{
			break;
		}
		pr=a[m+1][n];//previous element to swap
		for(i=m;i<c;i++)//rotates the top row
		{
			cr=a[m][i];
			a[m][i]=pr;
			pr=cr;
		}
		for(i=m+1;i<r;i++)//rotates the right column
		{
			cr=a[i][c-1];
			a[i][c-1]=pr;
			pr=cr;
		}
		for(i=c-2;i>=m;i--)//rotates the bottom row
		{
			cr=a[r-1][i];
			a[r-1][i]=pr;
			pr=cr;
		}
		for(i=r-2;i>m;i--)//rotates the left column
		{
			cr=a[i][n];
			a[i][n]=pr;
			pr=cr;
		}
		r--;c--;//decrements row and column for another rotation
		m++;n++;
	}
	printf("After rotation:\n");
	for(i=0;i<x;i++)
	{
		for(j=0;j<y;j++)
		{
			printf("%d ",a[i][j]);
		}
		printf("\n");
	}
	getch();
}

 

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.

Leave a Reply

Your email address will not be published.

1 × 4 =