In this program takes three enters from user which is stored in variable a, b and c respectively. Then, these variables are passed to function using call by reference. This function swaps the value of these elements in cyclic order.
C++ Program to Swap Elements Using Call by Reference
#include<iostream>
using namespace std;
void cycle(int *a,int *b,int *c);
int main(){
int a,b,c;
cout << "Enter value of a, b and c respectively: ";
cin >> a >> b >> c;
cout << "Value before swapping: " << endl;
cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl;
cycle(&a,&b,&c);
cout << "Value after swapping numbers in cycle: " << endl;
cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl;
return 0;
}
void cycle(int *a,int *b,int *c){
int temp;
temp=*b;
*b=*a;
*a=*c;
*c=temp;
}
Output
Enter value of a, b and c respectively: 1
2
3
Value before swapping:
a=1
b=2
c=3
Value after swapping numbers in cycle:
a=3
b=1
c=2