Swapping without third variable – Computer Sir Ki Class

Login


Lost your password?

Don't have an account ?
Register (It's FREE) ×
  

Login
[lwa]



Exam Questions-ICSE2015-02E #JAVA#3968    siteicon   siteicon  

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


Share

sunmitra| Created: 22-Mar-2018 | Updated: 16-Apr-2019|ICSE2015






Back