Exercise:
Write a C++ program that can swap numbers in cyclic order by calling references.
Click Here to View Solution:
#include <iostream>
using namespace std;
void cycSwap(int *x, int *y, int *z);
int main()
{
int x, y, z;
cout << "Insert 3 values:\n";
cin >> x >> y >> z;
cout << "\nBefore cyclic swapping:" << endl;
cout << x << ", " << y << ", " << z << endl;
cycSwap(&x, &y, &z); //function calling
cout << "\nAfter cyclic swapping:" << endl;
cout << x << ", " << y << ", " << z << endl;
return 0;
}
void cycSwap(int *x, int *y, int *z)
{
int temp;
temp = *y;
*y = *x;
*x = *z;
*z = temp;
}
Click Here to View Output:
Insert 3 values: 12 23 34 Before cyclic swapping: 12, 23, 34 After cyclic swapping: 34, 12, 23
Click Here to View Explanation:
- 3 numbers
x
,y
, andz
are taken from the user that have to be swapped in a cyclic order. A function is createdcycSwap ()
. - When creating function, instead of using the variable itself, the address of a variable is used in the
user-defined function
. - The values of
x
,y
, andz
are swapped automatically in themain ()
function when they’re swapped in thecycSwap ()
function. - Since no variables are directly used in
cycSwap ()
function, the values don’t have to be returned.