C++ Program to Swap Two Number

C++ Program to Swap Two Number | In this tutorial, We will swap two Numbers using a temporary variable or without using any temporary variable. To write this program you should understand what is data types in C++.  There are various methods to swap two numbers.

C++ program to swap two Number using the third variable

#include<iostream>
using namespace std;
int main()
{
  float num1, num2, temp;

  cout << "Enter two Number: ";
  cin >> num1 >> num2;

  //Display Numbers before Swapping
  cout << "Before Swap," << endl;
  cout << "num1 = " << num1 << endl;
  cout << "num2 = " << num2 << endl;

  //Swap num1 and num2
  temp = num1;
  num1 = num2;
  num2 = temp;

  //Display Numbers after Swapping
  cout << "\nAfter Swap," << endl;
  cout << "num1 = " << num1 << endl;
  cout << "num2 = " << num2 << endl;

  return 0;
}

Output:-

Enter two Number: 12 15
Before Swap,
num1 = 12
num2 = 15

After Swap,
num1 = 15
num2 = 12

C++ program to swap two Number without using any third variable

Here we will use arithmetic operators + and to swap two number.

#include<iostream>
using namespace std;
int main()
{
  int n1, n2;

  cout << "Enter two Number: ";
  cin >> n1 >> n2;

  n1 = n1 + n2;
  n2 = n1 - n2;
  n1 = n1 - n2;

  cout << "After swap:" << endl;
  cout << n1 << " " << n2 << endl;

  return 0;
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Learn More C++ Programming Examples,

Leave a Comment

Your email address will not be published. Required fields are marked *