here's an example program that swaps the values of two integers using a function with reference variables:
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:
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