Please help. Why numbers don't swap? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1
4th Jul 2020, 8:20 AM
Георгий Чуйко
4 Answers
+ 10
Георгий Чуйко you can swap two numbers without using a temporary or third variable if you can store the sum of numbers in one number and then minus the sum with other number something like: a = 3; b = 5; a = a + b; // 8 b = a - b;  // 3 a = a - b;  // 5 a = a + b; b = a - b; // actually (a + b) - (b),                 // so now b is equal to a. a = a - b; // (a + b) - (a),                 // now a is equal to b. Now you have a = 5 and b = 3, so numbers are swapped without using a third or temp variable.
4th Jul 2020, 9:50 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 4
Use this int x = 5; int y = 6; int swap; SOPln("input" + x "and" + y); //Swapping part swap=a; a=b; b=swap; SOPln("output" + x + "and" + y); //end
4th Jul 2020, 8:26 AM
Nilesh
+ 2
Thanks
4th Jul 2020, 9:11 AM
Георгий Чуйко