Using c++ how would I shift an integer array to the right?

Home » Programming & Design » Using c++ how would I shift an integer array to the right?
Programming & Design No Comments

I have to write a function taking in an integer array (arr[]), its length (N), and the number of elements to right-shift (M).
My current function looks like this and according to my tutor it is only a few lines away from working. Yet, it does not work and I don't have any idea how to make it work.

#include

I have to write a function taking in an integer array (arr[]), its length (N), and the number of elements to right-shift (M).
My current function looks like this and according to my tutor it is only a few lines away from working. Yet, it does not work and I don't have any idea how to make it work.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void shiftright (int myarray[], int size);

int main (void)
{
int myarray []= {1, 2, 3, 4, 5};

shiftright( myarray, 5);

for ( int i=0; i<5; i++)
{
cout << myarray[i] << ' ';
}

return(0);

}

void shiftright (int myarray[], int size, int M)
{
for (int m = (size-1); m>=1; m–){
int temp = myarray[size-1];

for (int i=(size- 1); i>=1; i–)
{
myarray[i] = myarray[i-1] ;
}
myarray[0] = temp;
}

}

Other answer:

Josh:
Hi,

To "move rightwards" you have to iterate from the end of array.

For example (Note using … to show indentation):

for(int j = array_size – 2; j >= 0; j–) {
…x[m+j] = x[j];
…cout << x[j] << endl;
}

If you do not subtract 2 from array size you will end up over writing whatever is in arr[0] onto the other elements in the array. Also, when you compile / execute you will get the dreaded Undefined Behavior: "off by one" trying to access the element beyond the array end error message.

Regards,

Timothy

Anas Imtiaz:
You have already asked this question and I provided the answer: https://answers.yahoo.com/question/index…
Impaled:
void shiftright (int myarray[], int size)
{
int last = myarray[size-1];
for (int m = (size-1); m>0; m–) {
myarray[i] = myarray[i-1] ;
}
myarray[0] = last;
}
Alex:
I

LEAVE A COMMENT