Swapping/Swap without using third variable in C/C++
It was never been so hard
to swap number variables without using third variable, however there are many
ways to do it but it seems that swapping variables using addition and subtraction
operators are the best way to go.
For instance, assume two
number variables ‘a’ and ‘b’
a = 10; b = 12;
Now, if a = a + b; then ‘a’
would be 22. Hence, ‘a’ is a combination of ‘a’ and ‘b’ , so if ‘b’ is
subtracted from ‘a’ , it will return the value of ‘a’.
a = a + b; // summation
of both 22
b = a – b; // remain the ‘a’,
which we are taking in b. 22 – 12 = 10
a = a – b; // remain the ‘b’,
which we are taking in b. 22 – 10 = 12
Now we can see the code
for swapping variables using addition (+) and subtraction (-) operator without
using the third variable:
(See the code very carefully how pointers in functions
can help to use the memory location to swap)
/* |
Author : Alim Ul Karim |
|------------------------------------------|
| Code tested on CodeBlocks , GCC Compiler
|
| Example of Swapping in C/C++, Save in .cpp |
|------------------------------------------|
*/
#include
<stdio.h>
//using without using third
variable, using addition and subtraction , save as .cpp file
void swap_using_add(int &a, int &b){
//no need to change if a=b
if ( a == b
){
return;}
a = a +
b;
b = a -
b;
a = a -
b;
}
int main(){
// save as .cpp
file
int a =
10 , b = 12;
int backup_a =
a , backup_b =
b;
swap_using_add(a , b); // save file as a .cpp format
printf("Swap using addition, subtraction :\nFrom(a=%d,b=%d) to a=%d , b=%d\n\n"
,
backup_a ,
backup_b , a ,b);
return 0;
}
|
Search Engine Friendly Links:
-
Swapping numbers without third variable
-
Swapping numbers without third variable using addition(+)
-
Swap number variable without third variable using addition(+)
-
Swap variables using addition(+) without the third variable
-
Swapping variable using addition(+)
-
Swap variable using addition(+)
-
Swap variable without the third
-
Swapping variable without the third
-
Swapping variable without the third in C
-
Swap variable using addition(+) in C++
Author:
Search Engine Friendly Labels:
No comments:
Post a Comment