Sunday, March 19, 2017

Program in C plus plus to swap two numbers with out a third variable

Give two numbers of we want to swap them, the commonly used method is to swap them using a third variable as shown below.


But the use of third variable is not really needed and some times not recommended as it leads to unnecessary memory usage. We can swap the two numbers using the bitwise XOR operation too as shown below.



Example:



The same program implemented in c plus plus below. The compilation and output are shown as run in Linux terminal using g++ compiler.

save the above program as swap_with_out_temp.cpp Compile and Execute :

Output:


No comments:

Post a Comment