Introduction: Swapping
the value of two numbers in C++ is not a difficult task. But how many of us
actually know that there are multiple ways to swap the value of two numbers/variables in C++ language. There are a number of ways to swap the value of two numbers in
C++. In this article I am going to use
Addition (+) and Subtraction (–) arithmetic operators to help in swapping. In my
previous article i explained "What is C++ Language ? Calculate sum of two numbers in C++ Language" and
“How to swap two numbers in C++ Language” i explained how to swap two numbers using temporary variable in C++. .
Implementation: Let's create a program to swap the value of 2 numbers.
“How to swap two numbers in C++ Language” i explained how to swap two numbers using temporary variable in C++. .
Implementation: Let's create a program to swap the value of 2 numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b;
cout<<"Enter first number= ";
cin>>a;
cout<<"Enter second number= ";
cin>>b;
cout<<"\nValue of first number
before swapping= "<<a;
cout<<"\nValue of second number
before swapping= "<<b;
a=a+b;
b=a-b;
a=a-b;
cout<<"\nValue of first number
after swapping= "<<a;
cout<<"\nValue of second number
after swapping= "<<b;
getch();
}
Run the program using ctrl+F9
Output:
Enter first number= 20
Enter second number= 50
Value of first number before swapping= 20
Value of second number before swapping= 50
Value of first number after swapping= 50
Value of second number after swapping= 20
Now over to you:
"If you like my work; you can appreciate by leaving your comments,
hitting Facebook like button, following on Google+, Twitter, Linked in and
Pinterest, stumbling my posts on stumble upon and subscribing for receiving
free updates directly to your inbox . Stay tuned and stay connected for more
technical updates."
If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..