// 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:

  1. The #include <iostream> directive includes the necessary header file for input and output operations.

  2. The swap function is defined to swap the values of two integers using references. The int &a and int &b parameters indicate that the function takes references to integers as arguments.

  3. Inside the swap function, a temporary variable temp is used to temporarily hold the value of a before the swap.

  4. The values of a and b are then swapped, with a taking on the value of b and vice versa.

  5. In the main function, two integers num1 and num2 are declared and initialized with values 5 and 10, respectively.

  6. The values of num1 and num2 are displayed before the swapping using std::cout.

  7. The swap function is called with num1 and num2 as arguments, causing the values to be swapped.

  8. The values of num1 and num2 are displayed again after the swapping using std::cout.

  9. The return 0; statement indicates the successful execution of the program.