All about programming in GNU/LINUX

Generic Code to move a given set of consecutive members of your choice,in an array, to the end of the array

#include<stdio.h>
#include<stdlib.h>
void rotate(void *front,void *middle,void *back)
{
    int frontsize=(char *)middle-(char *)front;
    int backsize=(char *)back-(char *)middle;
    char buffer[frontsize];//This declaration works fine in Code blocks compiler or GCC but ANSI doesnot support such declaration
    memcpy(buffer,front,frontsize);
    memmove(front,middle,backsize);//built in function to be noted down
    memcpy((char *)back-frontsize,buffer,frontsize);

}

int main()
{
    int n,begin,end,i;
    printf("\nEnter the size of the array: ");
    scanf("%d",&n);
    int array[n];
    for(i=0;i<n;i++)
    {
        array[i]=i+1;
    }
    printf("\nEner the positions of elements starting from - to -  you would wish to move it to end of the array: ");
    scanf("%d %d",&begin,&end);
    if(begin<0||end>n)
     {
         printf("\nInvalid entry");
         exit(0);
     }

  rotate(&array[begin-1],&array[end],&array[n]);
  printf("\nThe shifted array is: ");
  for(i=0;i<n;i++)
   printf("\t%d",array[i]);
  return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s