Hi im trying to get my array to display 5,1,2,3,4 from the original 1,2,3,4,5.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void values::movevalues()
{
cout << "postcondition\n";
int lastElement = numbers[5];
for(int i = 0; i <= 5; i++)
numbers[i+1] = numbers[i];
numbers[0] = lastElement;
for(int i = 0; i < 5; i++)
cout << numbers[5] << endl;
}
something in this part is making it go wrong, it displayes the original array fine but when it tries to shift it it goes haywire. Help would be appreciated.
EDIT: also how would i add elements onto the array?
Look at your for loop on line 7; when i is 4 or 5, you will be assigning to numbers[5] and numbers[6], which is out of bounds. You are pretty close to doing in correctly, so think carefully about what values you want to shift and you should be able to come up with the changes you need to make.
Also, on line 13 you are printing numbers[5] (which is out of bounds) instead of the presumably intended numbers[i].
Don't forget that the first index is 0 and as your array holds 5 elements the last index will be 4 and not 5. So, to read the last element you will need:
Ok cool, i made the changes needed (array is now 0,1,2,3,4, and int lastElement = numbers[4];). It still comes with weird numbers though :(. Could it be im calling it wrong in the main function? i just have it set to
1 2 3 4 5 6 7 8 9
int main ()
{
values okay;
okay.movevalues();
system ("pause");
return(0);
}
You're right about the array being different, that looks to be the reason it was displaying wrong numbers. This is just difficult for me since im barley learning arrays. Its confusing how i get from values() to movevalues() but still keep the same arrray
values::values()
{
cout << "pre\n";
// remove the following line: This will hide (and override) values::numbers
// int numbers[5] = {1,2,3,4,5};
for (int i = 0; i < 5; i++)
{
numbers[i] = i;
cout << numbers[i] << endl;
}
}
The reason is this:
Once you re-declare the array, the class's array is HIDDEN.
If you want to access the class's array, you are FORCED to use this->numbers, because accessing numbers will access the array which is ONLY available in the constructor.
In fact you ARE creating an array 1 to 5, but as soon as the constructor ends, the array ends too, because you redeclared it.
Holy crap dude, thank you so much. Now instead of those random numbers i get the last being shifted to the front :) thank you. I knew i was doing something dumb.