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++.


Number is: 10 20

After swap: 20 10


Example: How to swap two numbers using structure by reference in C++

Run it Now
#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 << "\nAfter 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