Showing posts with label swaping. Show all posts
Showing posts with label swaping. Show all posts

Wednesday, May 7, 2014

Swap 2 numbers without using third variable

This is a very very very simple question generally asked as first level of logical questions

Swap 2 numbers without using third variable


function fnSwap(a,b){
   console.log("Initial value of a: "+ a);
   console.log("Initial value of b: "+ b);

   // swaping the values of a and b
    b = a+b
    a = b-a
    b = b-a
    console.log("Swaped value of a: "+ a);
   console.log("Swaped value of b: "+ b);
}

Input:

fnSwap(10,20);


output:

Initial value of a: 10
Initial value of b: 20
Swaped value of a: 20
Swaped value of b: 10

Note:
It works with console if you are working with firefox install firebug to see output in console
if you install chrome/IE you can use f12 for console