C++ program to swap two numbers using call by reference

Last updated:4th Sep 2022

In this example, we will write a c++ program to swap two numbers entered by the user by using the call by reference method.

input:
a = 5 b = 10
output:
a = 10 b = 5

#include<iostream>
using namespace std;

// Function Prototype
void swapnumber(int * , int * );

int main() {
  int a, b;
  cout << "Enter Two Numbers: ";
  cin >> a >> b;
  printf("before swapping: a=%d b=%d\n", a, b);
  // Pass reference
  swapnumber( &a, &b);
  printf("After swapping: a=%d b=%d\n", a, b);
  return 0;
}

/* Function to swap two variables by reference */
void swapnumber(int *x, int *y) {
  int t;
  t = *x;
  *x = *y;
  *y = t;
}
output
Enter Two Numbers: 5    10
before swapping: a=5 b=10
After swapping: a=10 b=5

Related programs