C++ Program to Swap Numbers in Cyclic Order Using Call by Reference

C++ProgrammingServer Side Programming

Three numbers can be swapped in cyclic order by passing them to a function cyclicSwapping() using call by reference. This function swaps the numbers in a cyclic fashion.

The program to swap numbers in cyclic order using call by reference is given as follows −

Example

 Live Demo

#include<iostream>
using namespace std;
void cyclicSwapping(int *x, int *y, int *z) {
   int temp;
   temp = *y;
   *y = *x;
   *x = *z;
   *z = temp;
}
int main() {
   int x, y, z;

   cout << "Enter the values of 3 numbers: "<<endl;
   cin >> x >> y >> z;

   cout << "Number values before cyclic swapping..." << endl;
   cout << "x = "<< x <<endl;
   cout << "y = "<< y <<endl;
   cout << "z = "<< z <<endl;

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

   cout << "Number values after cyclic swapping..." << endl;
   cout << "x = "<< x <<endl;
   cout << "y = "<< y <<endl;
   cout << "z = "<< z <<endl;

   return 0;
}

Output

The output of the above program is as follows −

Enter the values of 3 numbers: 2 5 7
Number values before cyclic swapping...
x = 2
y = 5
z = 7

Number values after cyclic swapping...
x = 7
y = 2
z = 5

In the above program, the function cyclicSwapping() swaps the three numbers in cyclic order using call by reference. The function uses a variable temp to do so. The code snippet for this is as follows −

void cyclicSwapping(int *x, int *y, int *z) {
   int temp;
   temp = *y;
   *y = *x;
   *x = *z;
   *z = temp;
}

In the function main(), the values of the 3 numbers are provided by the users. Then these values are displayed before swapping them. The function cyclicSwapping() is called to swap the numbers and then the values are displayed after swapping them. This is given below −

cout << "Enter the values of 3 numbers: "<<endl;
cin >> x >> y >> z;

cout << "Number values before cyclic swapping..." << endl;
cout << "x = "<< x <<endl;
cout << "y = "<< y <<endl;
cout << "z = "<< z <<endl;

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

cout << "Number values after cyclic swapping..." << endl;
cout << "x = "<< x <<endl;
cout << "y = "<< y <<endl;
cout << "z = "<< z <<endl;
raja
Published on 23-Oct-2018 11:51:49
Advertisements