Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the definition of a function named rotate4ints that is passed four int var

ID: 3641326 • Letter: W

Question

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&,int&,int&,int&);

void rotate4ints(int& i,int& j,int& k,int& m)
{
i=m;
j=i;
k=j;
m=k;
}

Explanation / Answer

You'll need an extra variable to store value of i (or you can choose j, k or m)

void rotate4ints(int& i,int& j,int& k,int& m)
{
    int temp = i; //you have back up the value of i, now you can assign other value to i
    i = m; //now you have use the value of m and therefore you don't need to back up m. Next assign k to m
    m = k; //similar to m, now assign other value to k
    k = j; //assign j next
    j = temp; //this is where you need the original value of i, which is stored in temp
}