A Few days back when I was in Delhi, one student asked me how to write a c Plus Plus program to swap two numbers by using the temp variable. I had make understand the logic behind this program to that student and said I will write this program for you.
This is a very simple & easy C++ (C Plus Plus) program for number swapping. In the below program, we swapped two numbers using the temporary variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> using namespace std; int main() { int x = 5, y = 10, temp; cout << "Before swapping." << endl; cout << "x = " << x << ", y = " << y << endl; temp = x; x = y; y = temp; cout << "\nAfter swapping." << endl; cout << "x = " << x << ", y = " << y << endl; return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include<iostream.h> #include<conio.h> void main() { int a,b; clrscr(); cout<<"Enter value of a: "; cin>>a; cout<<"Enter value of b: "; cin>>b; a=a+b; b=a-b; a=a-b; cout<<"After swap a: "<<a<<"b: "<<b; getch(); } |
Before swapping.
x = 15, y = 10
After swapping.
x = 10, y = 15
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: Number Swapping, Number Swapping program, Number Swapping using the temporary variable. c plus plus tutorial, temporary variable