0

Im trying to make a program that shifts all my elements of array to the right by one and move the last element
into the first position.how would i move the last number out then shift numbers over then move the last number back
into the fist position? here is my code

 #include <stdio.h>

        int main ()
          {
            int array[6];
            int x;
            int temp;

           printf("Enter six numbers.\n\n");

// ---------- gets numbers from user -------------------          
            for(x = 0; x < 6; x++) {
                printf ("Enter a number : ", x+1);
                scanf ("%d",&array[x]);
            }

// ----------------- move the last guy out -------------------

          //this is what i need help with

// ----------------- shift everybody over ---------------------      
       for(x = 6; x > 0; x--)
        {
            array[x]=array[x-1];
        }
// ------------------  put the last guy back into the first one ------          

// --------------------  print the array contents -------------------       
       for(x = 0; x < 6; x++)
       {

         printf("%d\n", array[x]);

       }

         return 0;
}

Edited by Reverend Jim: Moved to programming forum

2
Contributors
3
Replies
17
Views
1 Month
Discussion Span
Last Post by ddanbe
0

Use a temporary variable to store the last element of the array. Why not call it temp?
Do your shift to the right.
Assign temp to the first element of your array.

0

yeah i tried that at first can you help me with that logic please this is what I tried

// ----------------- move the last guy out -------------------

        temp=array[6];

// ----------------- shift everybody over ---------------------      
       for(x = 6; x > 0; x--)
        {
            array[x]=array[x-1];
        }

// ------------------  put the last guy back into the first one ------          

         temp=array[6];

         array[6]=array[0];

         array[6]=temp; 

// --------------------  print the array contents -------------------       
       for(x = 0; x < 6; x++)
       {

         printf("%d\n", array[x]);

       }

         return 0;
}
0
Remove lines 13 to 17 and replace with: array[0]=temp; 

EDIT: Just noticed int array[6]; is an array that goes from 0 to 5.
On line 8 you are indexing with 6. But I guess you are able to fix that yourself. Success!

Edited by ddanbe: Addition

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.