• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Pro Programming

Professional way of Programming: Learn C, C++, Java, Python, Dot Net, Android the professional way

  • Home
  • C MCQs
  • C/C++ Programs
  • Java Programs
  • C#
  • Python
  • MySQL
  • Topics
    • Arrays
    • Strings
    • Link Lists
    • Trees
    • Shapes
  • Projects
  • Articles
  • Games

C++ Program to swap two numbers without using temporary variable

3 Comments

Today we are going to write a C++ program to swap two numbers without using any temporary variable, let’s start. There are many ways to swap two numbers without using a Temporary variable.

Here I’ve discussed two methods:

  1. Using ‘+’ and ‘-‘ operators.
  2. Using Bitwise XOR ‘^’.
There is another way to swap using call by reference method.

 

So here’s the First Program:

C++ Program to Swap two numbers using ‘+’ ‘-‘ operators.

#include<iostream>
using namespace std;
int main()
{
   int a, b;
   cout<<"Enter two integers to swap\n";
   cout<<"Enter a= ";
   cin>>a;
   cout<<"Enter b= ";
   cin>>b;
   a = a + b;   \\ ex. a=5,b=6  so,  here a = 5+6 = 11
   b = a - b;   \\  b= a-b i.e. b = 11-6 = 5
   a = a - b;   \\  a= a-b i.e. a = 11-5 = 6
   cout<<"\nAfter Swapping\n";
   cout<<"a = "<<a<<"\nb = "<<b;
   return 0;
}

 

OUTPUT:

 

Now let’s discuss the second method i.e. using the Bitwise XOR ‘^’.

 

C++ Program to Swap two numbers using Bitwise XOR ‘^’

#include<iostream>
using namespace std;
int main()
{
   int a, b;
   cout<<"Enter two integers to swap\n";
   cout<<"Enter a= ";
   cin>>a;
   cout<<"Enter b= ";
   cin>>b;
   a = a ^ b;
   b = a ^ b;
   a = a ^ b;
   cout<<"\nAfter Swapping\n";
   cout<<"a = "<<a<<"\nb = "<<b;
   return 0;
}

 

OUTPUT:

There many other ways in which we can do this like using call by reference etc. I’ve discussed the simplest one hope you like it, please comment if you have any other methods or any improvement for the above codes. Thank you.

Filed Under: cpp codes

  • « Go to Previous Page
  • Go to page 1
  • Interim pages omitted …
  • Go to page 64
  • Go to page 65
  • Go to page 66

Primary Sidebar

Recent Posts

  • 20 Golden Rules to Learn in Software Development
  • Total Quality Management Questions and Answers – Agile Manufacturing
  • How to Become a Cyber Security Engineer?
  • How to Become a Software Architect?
  • 7 Best Languages to Learn IoT Development in 2020
  • Privacy Policy
  • About
  • Contact US

© 2020 ProProgramming Privacy Policy About Contact Us