Monday 19 September 2011

Swap Numbers Without Using Third Variable Java Example

Swap Numbers Without Using Third Variable Java Example

  1. /*
  2. Swap Numbers Without Using Third Variable Java Example
  3. This Swap Numbers Java Example shows how to
  4. swap value of two numbers without using third variable using java.
  5. */
  6.  
  7. public class SwapElementsWithoutThirdVariableExample {
  8.  
  9. public static void main(String[] args) {
  10.  
  11. int num1 = 10;
  12. int num2 = 20;
  13.  
  14. System.out.println("Before Swapping");
  15. System.out.println("Value of num1 is :" + num1);
  16. System.out.println("Value of num2 is :" +num2);
  17.  
  18. //add both the numbers and assign it to first
  19. num1 = num1 + num2;
  20. num2 = num1 - num2;
  21. num1 = num1 - num2;
  22.  
  23. System.out.println("Before Swapping");
  24. System.out.println("Value of num1 is :" + num1);
  25. System.out.println("Value of num2 is :" +num2);
  26. }
  27.  
  28.  
  29. }
  30.  
  31. /*
  32. Output of Swap Numbers Without Using Third Variable example would be
  33. Before Swapping
  34. Value of num1 is :10
  35. Value of num2 is :20
  36. Before Swapping
  37. Value of num1 is :20
  38. Value of num2 is :10
  39. */

1 comment:

  1. num1 = num1 + num2;

    num2 = num1 - num2;

    num1 = num1 - num2;

    instead of this. i will tell you one simple algorithm for swapping

    num1 = num1 + num2 - (num2 = num1) ;

    num1 = 10;
    num2 = 20;

    apply the above algorithm

    num1 = num1 + num2 - (num2 = num1) ;
    num1 = 10+20-(num2 = 10);

    num1 = 30-10 = 20
    num2 = 10

    follow http://magentoworld.blogspot.com/ to build professional web store

    ReplyDelete

Complete Details about eLitmus pH Test at Rs:699/- Share your java material and fresher interview Information for us to Help Others... mail to : vhkrishnan.v@gmail.com