Swaping two variables without temporary variable and without standard function - POST - 3

 


  • int a = 32;
  • int b = 64;
  • swap the variables
                                                       Solution
        1. Many of us know we can swap two variable using a temporary variable as shown below.
    • int temp;
    • int temp = a;
    • int a = b;
    • int b = temp;
    • Now a and b are swapped using a temporary variable
        2. We can also use standard functions like swap .

        3. Now below algorithm helps us to avoid above two approaches.
    • a = a + b ;
    • b = a - 2*b ;
    • a = (a - b) / 2 ;
    • b = b + a ;
    • Thus we can swap with simple algorithms
        4.Here is another algorithm helps us swap without temporary variable
    • a = a + b;
    • b = a - b;
    • a = a - b;
        5.Here is another algorithm helps us swap without temporary variable
    • a = a ^ b;
    • b = a ^ b;
    • a = a ^ b;    



Guys if you have any doubts, please let me know

Post a Comment (0)
Previous Post Next Post

How to start Coding | coding for beginners | Lecture 1