Saturday, 28 December 2013

Multiple Logics to Swap Two Numbers in any Programming Language

This Question is sometimes used to see the analytic ability of a person and how dynamic thinking they have. The logic is same for all programming language, so if you have the logic right then you can answer it for any particular language such as PHP, JAVA, C++, C, C# etc. 

With using a third variable :-

Logic No.1 : temp=a; a=b; b=temp;


Without using a third variable :-

Logic No.2 : a=a+b; b=a-b; a=a-b;
Logic No.3 : a=a/b; b=a*b; a=(1/a)*b;
Logic No.4 : a=a*b; b=a/b; a=a/b;
Logic No.5 : a=(a+b)-(b=a);


That’s it!!…..Happy Programming...

2 comments:

  1. can u evaluate your logic 5?

    ReplyDelete
  2. For example a=5 and b=10
    Now according to logic number 5 :-
    a=(5+10)-(b=a)
    value of a assigned to b
    a=(5+10)-(5)
    a=10
    b=5
    That's it

    ReplyDelete