Google News
logo
C++ Program to Swap Numbers in Cyclic Order Using Call by Reference
In the following example of C++ program to swap numbers in cyclic order using call by reference :
Program :
#include <iostream>
using namespace std;

void cyclicSwap(int &a, int &b, int &c);

int main() {
   int a, b, c;
   cout << "Enter three numbers: ";
   cin >> a >> b >> c;
   cyclicSwap(a, b, c);
   cout << "After cyclic swap: " << endl;
   cout << "a = " << a << endl;
   cout << "b = " << b << endl;
   cout << "c = " << c << endl;
   return 0;
}

void cyclicSwap(int &a, int &b, int &c) {
   int temp = a;
   a = c;
   c = b;
   b = temp;
}
Output :
Enter three numbers: 1
2
3
After cyclic swap: 
a = 3
b = 1
c = 2
In this program, we define a function cyclicSwap() which takes three integer arguments passed by reference.

Inside the function, we use a temporary variable temp to hold the value of the first variable a. We then assign the value of the third variable c to the first variable a, the value of the second variable b to the third variable c, and finally, the value of the temporary variable temp to the second variable b.

We call the function cyclicSwap() by passing the three numbers entered by the user as arguments. The values of the variables a, b, and c are then swapped in a cyclic order.

Finally, we display the swapped values of the variables a, b, and c using cout.