Help w/ Shifting Arrays to Right

Hi I'm trying to write a program that assigns random numbers to an array and then shifts the numbers in the array one unit to the right and returns the last number in the array to the first index. I've got it to shift them to the right and in the "test array" where I initialize values to 0,1,2..etc. it will move the 9 to the first index but when I run it with the random numbers it displays a 1 for the first index. I'm not sure what's wrong so any help would be appreciated.


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
39
40
41
42
43
44
45
46
47
48
49
50
#include<iostream>
#include<time>
using namespace std;

const int MAX=10;

int main()
{
    //declare array and variables
    //int list[MAX]={0,1,2,3,4,5,6,7,8,9}; //A test array before changing values to random numbers
    int list[MAX];
   	int temp = list[MAX-1]; // stores last number in index to temporary value.



		    //initialize random number generator
			srand((unsigned)time(NULL));

			//fill array with random numbers
			for(int index=0;index<MAX;index++)
			{
			list[index]=rand()%100;
			}


	//shift array to right
	for(int index=MAX-1;index>0;index--)
	{
	list[index]=list[index-1];
	}
	list[0]=temp; //reassigns first value in list[index] to the stored temporary value



    //display array
     cout<<"[";
	    for(int index=0;index<MAX;index++)
		    {
		    if (index>0 && index<10)
			cout<<", "; //seperated by a comma and a space

		    cout<<list[index];
			}
			cout<< "]";

	cout<<endl;


    system("pause");
}
Note that you assign a value to temp on line 12 from list[MAX-1]. That element is given a different value on line 22, but the value stored in temp remains the same. So when you reach line 31, temp does not reflect the value that was stored in list[MAX-1].
Last edited on
Topic archived. No new replies allowed.