Reputation: 23
"Write a program that allows a user to input an integer for the size of an array. Using Malloc is recommended. Randomly generate an integer for each element of the array. Next, creating a funcion to rotate the array. Rotation of the array means that each element is shifted right or left by one index, and the last element of the array is also moved to the first place"
Example: 31 83 91
Which direction to shift and how many times?- Left
How many times would you like to shift? 2
End Result: 91 31 83
Currently my 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 would you like in your array?\n");
scanf("%d", &SlotNumber);
for(i=0;i<SlotNumber;i++){
printf("%d \t", rand());
}
ptr = (int *)malloc(SlotNumber*sizeof(int));
printf("\nWhich direction would you like to shift it to? R/L?\n");
scanf(" %c", &direction);
printf("\nHow many times would you like to 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;
}
Upvotes: 1
Views: 3744
Reputation: 28654
There were few problems with your code. Here is improved solution with left shift, right shift I leave to 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 would you like in your array?\n");
scanf("%d", &SlotNumber);
ptr = malloc(SlotNumber*sizeof(int));
// Fill array with random numbers
for(i=0;i < SlotNumber; i++)
{
ptr[i]=rand();
printf("%d \t",ptr[i]);
}
printf("\nHow many times would you like to shift?\n");
scanf("%d", &ShiftAmount);
for(i=0; i < 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; i < SlotNumber; i++)
{
printf("%d \t",ptr[i]);
}
free(ptr);
return 0;
}
Upvotes: 1