// A C++ program to show that we can use reference to
#include <iostream>
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int num1 = 5, num2 = 10;
std::cout << "Before swapping:" << std::endl;
std::cout << "num1 = " << num1 << std::endl;
std::cout << "num2 = " << num2 << std::endl;
// Swapping using reference
swap(num1, num2);
std::cout << "After swapping:" << std::endl;
std::cout << "num1 = " << num1 << std::endl;
std::cout << "num2 = " << num2 << std::endl;
return 0;
}
Explanation:
The
#include <iostream>
directive includes the necessary header file for input and output operations.The
swap
function is defined to swap the values of two integers using references. Theint &a
andint &b
parameters indicate that the function takes references to integers as arguments.Inside the
swap
function, a temporary variabletemp
is used to temporarily hold the value ofa
before the swap.The values of
a
andb
are then swapped, witha
taking on the value ofb
and vice versa.In the
main
function, two integersnum1
andnum2
are declared and initialized with values 5 and 10, respectively.The values of
num1
andnum2
are displayed before the swapping usingstd::cout
.The
swap
function is called withnum1
andnum2
as arguments, causing the values to be swapped.The values of
num1
andnum2
are displayed again after the swapping usingstd::cout
.The
return 0;
statement indicates the successful execution of the program.