This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Wednesday, March 15, 2023

Write a function using reference variables as arguments to swap the values of a pair of integers in a program

 here's an example program that swaps the values of two integers using a function with reference variables:

#include <iostream>
using namespace std;

// function to swap two integers using reference variables
void swap(int& x, int& y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    int num1 = 10, num2 = 20;
    
    // before swapping
    cout << "Before swapping: " << endl;
    cout << "num1 = " << num1 << ", num2 = " << num2 << endl;
    
    // swap the values of num1 and num2
    swap(num1, num2);
    
    // after swapping
    cout << "After swapping: " << endl;
    cout << "num1 = " << num1 << ", num2 = " << num2 << endl;
    
    return 0;
}

Output:

Before swapping:
num1 = 10, num2 = 20
After swapping:
num1 = 20, num2 = 10

In this program, the swap() function takes two integer arguments as reference variables (int&). Inside the function, the values of the variables are swapped using a temporary variable. In the main() function, two integers num1 and num2 are defined and their values are printed before and after swapping. The swap() function is called with num1 and num2 as arguments to swap their values. Finally, the new values of num1 and num2 are printed on the screen.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget