Swapping values of two variables is not a big task but when we need to swap two values without initialing a temporary variable is something which is to be appreciated. It’s not about any programming language but it’s about logic. This is not a big deal and you will understand that when you see the steps. Let’s try.
Open your C++ IDE on your desktop. I’m using Turbo C++ IDE on my desktop but coding are all same for both.
Create a new file and start your coding and in my Turbo C++, Go to “File” tab and click “new”. A pop up window will open where you start coding as I describe below.
Are the header file’s addresses in which the meaning of all the words used in the program are stored.
Functions used to clear the output screen from previous outputs and displaying the new outputs.
After initialing the variables “a” and “b” with values 10 and 20, values are displayed in output screen using “cout” method. The three line logic is next.
Output:
Now you understood swapping without a temporary variable is also a simple task.
Open your C++ IDE on your desktop. I’m using Turbo C++ IDE on my desktop but coding are all same for both.
#include<iostream.h>Here the
#include<conio.h>
Void main()
{
clrscr();
int a=10,b=20;
cout<< “a = “<<a<<” and b = “<<b<<”\n”;
a = a + b;
b = a - b;
a = a –b;
cout<< “a = “<<a<<” and b = “<<b<<”\n”;
getch();
}
- #include<iostream.h>
- #include<conio.h>
Are the header file’s addresses in which the meaning of all the words used in the program are stored.
- Clrscr() and getch()
Functions used to clear the output screen from previous outputs and displaying the new outputs.
After initialing the variables “a” and “b” with values 10 and 20, values are displayed in output screen using “cout” method. The three line logic is next.
a = a + b;
b = a - b;
a = a –b;
By this three lines the values are swapped and again with a “cout” method output is displayed.Output:
No comments