Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program to rotate the elements of an array a specified number of places

ID: 3625072 • Letter: W

Question

Write a program to rotate the elements of an array a specified number of places input by the user, with these specifications:

1. A positive number indicates a rotation to the right
2. A negative number indicates a rotation to the left (*extra challenge)
3. Use only pointer notation (not array notation) in the functions other than main
4. Do not declare additional space to hold an array outside of main; in other words, rotate the array "in place"
5. Use the main function given here; do not change it except to comment-out statements during development and test:

#define SIZE 10

/* function prototypes go here */

int main()
{
int a[SIZE] = {23, -3, 6, 19, 88, -5, 7, 34, -101, 88};
int places;

printf("Original array: ");
showArray(a, SIZE);
printf(" Rotate how many places (+/- for right/left)? ");
scanf("%d", &places);
rotate(a, SIZE, places);
printf(" Rotated array: ");
showArray(a, SIZE);

printf(" ");
system("pause");
return 0;
}

Explanation / Answer

#include<stdio.h>
#include<conio.h>
void showArray(int array[], int size);
void rotate(int array[],int SIZE,int places);
int main()
{
    const short SIZE = 10;
   int a[SIZE] = {23, -3, 6, 19, 88, -5, 7, 34, -101, 88};
   int places;
    printf("Original array: ");
   showArray(a, SIZE);
   printf(" Rotate how many places (+/- for right/left)? ");
   scanf("%d", &places);
   rotate(a, SIZE, places);
   printf(" Rotated array: ");
   showArray(a, SIZE);
   printf(" ");
   getch();
   return 0;
}
void showArray(int array[], int size)
{
    for(int i = 0; i < size; i++)
    {
        printf("%d ",array[i]);
    }
}
void rotate(int a[], int k, int p)
{
int temp,h;
int i;
if(p<0)
   {
    p = -p;
     for(h=0; h<p; h++)
     {
     temp = a[0];
             for(i=0; i<9; i++)
             {
             *(a+i) = *(a+i+1);
             }
             *(a+9) = temp;
     }
   }
   else {
        for(h=0; h<p; h++)
        {
        temp = a[9];
             for(i=9; i>0; i--)
             {
             *(a+i) = *(a+i-1);
             }
             *(a) = temp;
     }
        }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote