C++ Program to Swap Numbers in Cyclic Order Using Pointers

In this C++ program, we will swap the values of three integer variables in cyclic order using pointers.

For Example :
Let the A, B and C be three integer variables with value 1, 2 and 3 respectively. 
A = 1
B = 2
C = 3
After cyclic swap:
A = 2
B = 3
C = 1

Algorithm to perform cyclic swap of three variables
Let the A, B and C be three integer variables and temp be a temporary variable.
  • Store value of A in temp. temp = A;
  • Assign value of B to A. A = B;
  • Assign value of C to B. B = C;
  • Now, assign value of temp to C. C = temp;

C++ Program to Swap Numbers in Cyclic Order Using Pointers

#include<iostream>
using namespace std;

void swapCyclic(int *x, int *y, int *z){
    // Doing cyclic swap using a temporary variable 
    int temp;
    temp = *x;
    *x = *y;
    *y = *z;
    *z = temp;
}

int main() {
    int x, y, z;

    cout << "Enter three integers\n";
    cin >> x >> y >> z;

    cout << "Before Swapping\n";
    cout << "X = "<<x<<", Y = "<<y<<", Z = "<<z << endl;

    swapCyclic(&x, &y, &z);

    cout << "After Swapping\n";
    cout << "X = "<<x<<", Y = "<<y<<", Z = "<<z;

    return 0;
}
Output
Enter three integers
1 2 3
Before Swapping
X = 1, Y = 2, Z = 3
After Swapping
X = 2, Y = 3, Z = 1

We have defined a function "swapCyclic" which takes the address of three integer variables and perform cyclic swap of their values. As we are calling swapCyclic function using call by reference, any change in the values of variables in side function is reflected globally.

In this program, we will first take three numbers as input from user and store them in variable x, y and z. Then, we then call swapCyclic function by passing the address of x, y, and z using & operator. Finally we print the updated values of x, y, and z variable on screen using cout.