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

Hits: 24

(C++ programming Example for Beginners)

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

This program takes three integers from the user and swaps them in cyclic order using pointers.


Three variables entered by the user are stored in variables ab and c respectively.

Then, these variables are passed to the function cyclicSwap(). Instead of passing the actual variables, addresses of these variables are passed.

When these variables are swapped in cyclic order in the cyclicSwap() function, variables ab and c in the main function are also automatically swapped.

Example: Program to Swap Elements Using Call by Reference


#include<iostream>
using namespace std;

void cyclicSwap(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;

    cyclicSwap(&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 cyclicSwap(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

Notice that we haven’t returned any values from the cyclicSwap() function.

 

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

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.