moving elemnts in an array and displaying

This is for a class project. I am having trouble "pulling out" the last element in my array, shifting all the elements back then inserting that last value in the front. Then also displaying the array after the shift. here's my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include "stdafx.h"
#include<iostream>
using namespace std;


class values
{
public:
values();
void movevalues();


private:
int billy[5];

};
values::values()
{
cout<< "precondition\n";
int billy[5] = {1,2,3,4,5};
for (int i = 0; i <= 4; i++)
{
     std::cout << billy[i] << "\n";
}
}

void values::movevalues()
{
std::cout << "postcondition\n";
int temp = billy[0];

for (int i=0; i<=(4); i++)
{
    billy[i] = billy[i+1] ;
}	
billy[4] = temp;
std::cout <<billy[0] << "\n";
}
I didn't really take a close look at your code, but here is what I think you're getting at:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int values[5]; //integer array of 5, the values that are to be shifted

...

//display un-shifted array
for(int i = 0; i < 5; i++)
    std::cout << values[i] << std::endl;

std::cout << std::endl << "Shifting array..." << std::endl << std::endl;

//begin shift***
int lastElement = values[5]; //save the last value of the array

for(int i = 0; i < 4; i++) //shift all values from 0 to 4 over
    values[i + 1] = values[i];

values[0] = lastElement; //replace the first element with the saved last element
//end shift***

//display shifted array
for(int i = 0; i < 5; i++)
    std::cout << values[i] << std::endl;


Wrote this code in a hurry, sorry if I failed at something.
Last edited on
It would be good if you define some constant in your class that will denote the number of elements of the array. Also I would make a separate method that displays the array.

Function movevalues is invalid. Apart from accessing non-existent elements of the array it tries to shift the array left instead of right.
Last edited on
Big thanks to both of you. this was very helpful.
Topic archived. No new replies allowed.