Coders Packet

Swap numbers in C++

By Subalaxmi C

To swap the number of two variables without using an extra variable in C++ programming language.

We ask the user to enter two numbers which needs to be swapped. Then the user enters two numbers which is stored in the declared variables. 

Then we use this logic to swap the number of the two variables.

p = p + q;
q = p - q;
p = p - q;

Where both the variables are added and stored in the first variable, then both of them are subtracted from each other and stored in the second variable and then both of them are subtracted and stored in the first variable. 

If we see here the vaue of each variable changes everytime we equate it. Each time the compiler compiles the value of the variable it changes and that instant value is taken to equate in the next mathematical equation. 

Download Complete Code


No comments yet