Ozymandias Ozymandias - 18 days ago 6
C++ Question

Shifting an array to the right

I'm generating an array of random integers and trying to shift the values one to the right and replace the first element with the former last element.

The output is not ordered, and the final element is a randomly generated integer.

#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;


void shift(int values[], int size) {
int temp;
for (int i = 0; i < size; i++) {
temp = values[size - 1];
values[i] = values[i + 1];
values[0] = temp;
cout << values[i] << setw(4);
}
cout << endl;
}
int main()
{
cout << "Random 10 index array" << endl;
const int CAP = 10;
int numbers[CAP];

srand(time(0));
int i;
for (i = 0; i < CAP; i++) {
int rng = rand() % 100 + 1;
numbers[i] = rng;
cout << numbers[i] << setw(4);

}
cout << "shifting all elements to the right: " << endl;
shift(numbers, CAP);

cout << endl;
system("pause");
return 0;
}


I tried using
i < size - 1
, but I got 9 out of the 10 numbers I needed.

Answer

Here's the offending code:

        temp = values[size - 1]; 

This statement does not use the loop variable. Why is it sitting in the loop? This assignment will keep happening size-1 times.

        values[i] = values[i + 1];

Your loop invariant is i <size, yet you try to access i+1. That's just asking for trouble :). This is why you don't get garbage values when you use i < size-1.

        values[0] = temp;

Again, this doesn't use the loop variable. It doesn't belong in the loop. You just keep setting values[0]over and over again.

Here's a solution that works, using two temp variables:

void shift(int values[], int size) {
  7     int temp = values[size-1], temp1;
  8     for (int i = 0; i < size; i++) { 
  9         temp1 = values[i];
 10         values[i] = temp;
 11         temp = temp1;
 12         cout << values[i] << setw(4);
 13     }
 14     cout << endl;
 15 }