Reference Variables

The question is part of a programming lab and my code is wrong but I do not know why. Can someone teach me why the code for the following question is wrong?

Write the definition of a function named rotate4ints that is passed four int variables. The function returns nothing but rotates the values of the four variables: the first variable, gets the value of the last of the four, the second gets the value of the first, the third the value of the second, and the last (fourth) variable gets the value of the third. So, if i , j , k , and m have (respectively) the values 15, 47, 6 and 23, and the invocation rotate4ints(i,j,k,m) is made, then upon return, the values of i , j , k , and m will be 23, 15, 47 and 6 respectively.

void rotate4ints(int &i, int &j, int &k, int &m)

{
int i=m;
int j=i;
int k=j;
int m=k;
}
Make
1
2
3
4
int i=m;
int j=i;
int k=j;
int m=k;


in to

1
2
3
4
i=m;
j=i;
k=j;
m=k;


Also when the following line is reached
i=m
then i will be the same as m.
Then j will be the same as i. then m will be the same as k. So essentially your code makes all the variables equal each other. I doubt that's what you want
Last edited on
You are creating 4 local int variables in that function.
closed account (ihq4izwU)
hey gdookie. sorry for my dumb reply, since I still don't know much about functions, here's my tip.

int i=m;
int j=i;
int k=j;
int m=k;

just by looking onto how you initialize your variables. you could conclude that all the variables will have the same values. since for example;

a=1
b=2
c=3
d=4

just in time you call out your function rotate4ints(a,b,c,d) the result would be.
a = d which is 4, so a = 4
b = a which is 4, so b = 4
c = b which is 4, so c = 4
d = a which is 4, so d = 4
having an output of all the same value of your initialized 'k'.

a = 4
b = 4
c = 4
d = 4

I guess I am not capable of showing the correct code but at least I tried answering your post. Hope I helped =)
1
2
3
4
5
6
7
8
void rotate4ints( int &i, int &j, int &k, int &m )
{
   int tmp = m;
   m = k;
   k = j;
   j = i;
   i = tmp;
}

Thanks everyone! The portion of the textbook that covers reference variables is not very helpful for this question. Can someone elaborate on

int tmp = m;

I'm trying my best to learn but at times it appears a lost cause.
The value of m is being overwritten in the second statement but it will be needed in the last statement to assign it to i. So we are storing it in some intermediate variable tmp that to use it latter.
Again, thanks! I will most likely have additional requests although I work as hard as I can at solving the problems on my own before seeking outside assistance.
Topic archived. No new replies allowed.