C Program - Shifting Elements in an array -


"write program allows user input integer size of array. using malloc recommended. randomly generate integer each element of array. next, creating funcion rotate array. rotation of array means each element shifted right or left 1 index, , last element of array moved first place"

example: 31 83 91

which direction shift , how many times?- left

how many times shift? 2

end result: 91 31 83

currently code. it's not shifting.

#include <stdio.h> #include <stdlib.h>  int main(){  int i, temp, swapped; int slotnumber; int *ptr; char direction; int shiftamount;  printf("how many slots in array?\n"); scanf("%d", &slotnumber); for(i=0;i<slotnumber;i++){     printf("%d \t", rand()); } ptr = (int *)malloc(slotnumber*sizeof(int));  printf("\nwhich direction shift to? r/l?\n"); scanf(" %c", &direction); printf("\nhow many times shift?\n"); scanf("%d", &shiftamount);  if((direction=='r')||(direction=='r')){     while(1){         swapped = 0;         for(i=0;i<ptr+1;i++){             if(ptr[1]>ptr[i+shiftamount]){                 int temp = ptr[i];                 ptr[i] = ptr[i+shiftamount];                 ptr[i+shiftamount] =temp;                 swapped = 1;             }         }         if(swapped == 0);         break;     } } printf("\nnewlist\n"); for(i=0;i<ptr;i++){     printf("%d \t",ptr[i]); }  return 0; } 

there few problems code. here improved solution left shift, right shift leave you.

#include <stdio.h> #include <stdlib.h> #include <time.h>   int main() {      int i, j;     int slotnumber;     int *ptr;     int shiftamount;     int temp;      srand(time(null));      printf("how many slots in array?\n");     scanf("%d", &slotnumber);      ptr = malloc(slotnumber*sizeof(int));      // fill array random numbers     for(i=0;i < slotnumber; i++)     {         ptr[i]=rand();         printf("%d \t",ptr[i]);      }      printf("\nhow many times shift?\n");     scanf("%d", &shiftamount);       for(i=0; < shiftamount; i++)     {         temp = ptr[0];         for(j=0;j < slotnumber - 1;j++)         {             ptr[j] = ptr[j+1];         }         ptr[slotnumber - 1]=temp;     }      printf("\nnewlist\n");     for(i=0; < slotnumber; i++)     {         printf("%d \t",ptr[i]);     }      free(ptr);      return 0; } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -