How can we switch two variables values using only two variables..? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can we switch two variables values using only two variables..?

24th Sep 2018, 11:19 PM
Abdelhaq
Abdelhaq - avatar
3 Answers
+ 1
It's a data manipulation trick, there is more than one way. For integers: Use 1 variable to hold difference. Then use difference to swap the other over variable. Then use the value and difference get the other value back.
25th Sep 2018, 8:45 AM
Jared Bird
Jared Bird - avatar
+ 1
how ?
25th Sep 2018, 9:16 AM
Abdelhaq
Abdelhaq - avatar
+ 1
y = y - x; //y holds the difference x = x + y; //x holds the y value y = x - y; //y holds the x value;
26th Sep 2018, 10:23 AM
Jared Bird
Jared Bird - avatar