Summary: In this programming example, we will swap two numbers in C++ using call by reference and call by address.

Swap Numbers by Call by Reference

Output:

Enter two numbers A & B
5 3
Value of A before swapping: 5
Value of B before swapping: 3
Value of A after swapping: 3
Value of B after swapping: 5


In this example, we are passing the reference of a and b to the swapByReference method for the swapping process.

In the swapByReference method, we interchange the reference of the two variables using a temporary variable.

Swap Numbers by Call by Address

Output:

Enter two numbers A & B
9 5
Value of A before swapping: 9
Value of B before swapping: 5
Value of A after swapping: 5
Value of B after swapping: 9


In this method, we have used pointers to interchange the values of a and b.

Instead of value or reference, we pass the address of variables a and b to the swapUsingAddress method and swap their values by dereferencing the same.

Hope now you know, how to swap two numbers using reference and address in C++. If you have any doubts about the tutorial then comment below.

Leave a Reply

eighteen + 18 =