Skip to main content

Welcome to Coding 4 Programming

Addition of Two Binary Numbers | Function | Python

Swapping of Two Numbers without Third Variable | C++

   

Program of Swapping of Two Numbers without third variable entered by the user in C++


#include<iostream.h> 
#include<conio.h> 
void main()
{
 clrscr();
 cout<<"\n\t Welcome to Coding 4 Programming";
 int a,b,c;
 cout<<"\n\n\t Enter First Number=";
 cin>>a;
 cout<<"\t Enter Second Number=";
 cin>>b;
 cout<<"\n\t Value of a and b Before Swapping:";
 cout<<"\n\t a="<<a;
 cout<<"\n\t b="<<b;
 a=a+b;
 b=a-b;
 a=a-b;
 cout<<"\n\n\t Value of a and b After Swapping:";
 cout<<"\n\t a="<<a;
 cout<<"\n\t b="<<b;
 getch();
}


Output Screen:

C++ Coding


Notes:

1. Swapping means to inter change the values of variable. That means change the value of variable a into b and vice versa.

Concept of above Coding:

Main Concept of the above coding is from line 15 to line 17.

Illustration by example:

Let a=75 and b=22
In line 15, a become (a+b) 75+22=97.
In line 16, b become (a-b) 97-22=75.
In line 17, a become (a-b) 97-75=22. Note value of a has changed to 97 from 75 in line 15.
So, Now a=22 and b=75, 

Illustration of above Coding:


1. In Header Files (line 1 and line 2) .h is not required in some compilers.

2. iostream.h (line 1) header file is used for input (cin) and output (cout) services.

3. conio.h (line 2) header file is used for clrscr() and getch() functions.

4. Instead of void main (line 3) some may use int main.

5. Some new compiler required using namespace std; before main function (line 3).

6. clrscr() (line 5) function is used for clear the previous output on output screen.

7. \n is used for new or next line.

8. \t is used for giving tap space.

9. In line 7, we declared three variable of integer data type named (identifier) as aand ca and b for the number which user want to swap and c for the swapping of value with the help of third variable (c).

10. In line 8 and 10, program will display message on output screen to user for entering value of a (line 8) and b (line 10).

11. In line 9 and 11, program will take value of a (line 9) and b (line 11) entered by the users during running of program. 

12. From line 12 to line 14, we are displaying the initial value (Before Swapping) of a and b.

13. From line 15 to line 17, Program will swap the value of a and b (concept behind this illustrated above).

13. cin (line 9 and line 11) is used for taking the value of a (line 9) and b (line 11).

14. cout (line 6, 8, 10,12,13,14,18,19 and 20) is used for the display anything (content) on output screen.

15. getch() (line 21) function is used for freezing the output screen.

16. Braces i.e., {} (line 4 and line 22) is used for the block. That means from line 4 to line 15 is single block.

Comments

Popular Posts