C++ Program to swap two numbers using structure by reference
In this program, You will learn how to swap two numbers using structure by reference in C++.
The number is: 10 20
After swap: 20 10
Example: How to swap two numbers using structure by reference in C++.
#include<iostream>
using namespace std;
struct Test {
int x, y;
};
void swap(Test *t) {
int temp;
temp = (*t).x;
(*t).x = (*t).y;
(*t).y = temp;
}
int main() {
struct Test t;
cout << "Enter two numbers:";
cin >> t.x >> t.y;
swap(&t);
cout << "After swap x is:" << t.x;
cout << "\nAfter swap y is:" << t.y;
return 0;
}
Output:
Enter two numbers:10 20
After swap x is:20
After swap y is:10