I'm using the simplest approach to rotate array anti-clockwise i.e by storing elements from index=0 to index=number of rotating positions required, in a temporary array and finally inserting these elements int he end of another array. Here's the code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a, *temp, i, j=0, n,np,*b;
printf("Enter no. of elements in arr:\n");
scanf("%d",&n);
a=(int*) malloc(n*sizeof(int));//Primary array
b=(int*) malloc(n*sizeof(int));//Final array that would be printed in the end
printf("Enter elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter positions to be rotated anti-clockwise:\n");
scanf("%d",&np);
temp=(int*) malloc(np*sizeof(int));//storing elements left of index=0
for(i=0;i<np;i++,j++)
{
//printf("hi\n");
temp[j]=a[i];
printf("temp[%d]=%d\n",j,temp[j]);
}
j=0;
printf("After rotating:\n");
for(i=n-1;i>=0;i--)
{
printf("i=%d ",i);
b[i-np]=a[i];
printf("b[%d]=%d\n",i-np,b[i]); /*Here is 1 unexpected thing happening, the program is not picking up correct value of array a at index i.*/
}
for(i=np-1;i<n;i++,j++)
b[i]=temp[j];//storing temp elements in final array
printf("Finally matrix is\n");
for(i=0;i<n;i++)
printf("%d\n",b[i]);
getch();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire