Problem Statement - Swapping without third variable
What are the values of a and b after the following function is executed, if the values passed are 30 and 50.
void paws(int a, int b) {
a = a + b;
b = a - b;
a = a - b;
System.out.println(a + " , " + b);
}
Solution
TC++ #3968
This is a typical swap function without using third variable. Let us analyse –
a = 30 and b = 50
a = a+b ; //so a would be 80
b = a-b; //since a is now 80 it would be 80 – 50 = 30, so b would now have 30
a = a-b;//would be 80 – 30 (as b is now 30) so now a would be 50
so the output of
System.out.println(a+” , “+b) ; would be 50 , 30