C++ Program to Swap Two Numbers without using third variable

By | 23.12.2016

Swap Two Numbers without using third variable


Write a C++ Program to Swap Two Numbers without using third variable. C++ Program to Swap Two Numbers without  third variable. Here’s simple Program to Swap Two Numbers without using temp variable in C++ Programming Language.


Here is source code of the C++ Program to Swap Two Numbers without using third variable. The C++ program is successfully compiled and run(on Codeblocks) on a Windows system. The program output is also shown in below.


SOURCE CODE : :


/*  C++ Program to Swap Two Numbers without using third variable  */

#include <iostream>
using namespace std;

int main()
{

    int a,b ;

    cout<<"Enter 1st number :: ";
    cin>>a;
    cout<<"\nEnter 2nd number :: ";
    cin>>b;

    cout << "\nBefore swapping, Numbers are :: " << endl;
    cout << "\n\ta = " << a << ", b = " << b << endl;

    a = a + b;
    b = a - b;
    a = a - b;

    cout << "\nAfter swapping, Numbers are :: " << endl;
    cout << "\n\ta = " << a << ", b = " << b << endl;

    return 0;
}

Output : :


/*  C++ Program to Swap Two Numbers without using third variable  */

Enter 1st number :: 5

Enter 2nd number :: 9

Before swapping, Numbers are ::

        a = 5, b = 9

After swapping, Numbers are ::

        a = 9, b = 5

Process returned 0

Above is the source code for C++ Program to Swap Two Numbers without using third variable which is successfully compiled and run on Windows System.The Output of the program is shown above .

If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.


Thanks for reading the post….

5 6 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Gary Holveck

Thank you for these examples. My first was learning Commodore Basic “by doing”!

Hossam_Magdy

I solved it with this code
#include <iostream>
using namespace std;
int main()
{
short a, b;
cout << “The Values before Swap\n”;
cout << “Please enter the value of a\n”;
cin >> a;
cout << “Please enter the value of b\n”;
cin >> b;
cout << “The Values After the Swap\n”;
swap(a,b);
cout << “a = ” << a << endl;
cout << “b = ” << b << endl;
return 0;
}
Am i wrong?

krishna

your code absolutely right but in this (“”); you can try it.