Saturday 10 March 2012

Swap Numbers without using third variable

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.kota.java;

public class SwapNumbers {

  public static void main(String[] args) {
         
   int num1 = 10;
         int num2 = 20;
        
         System.out.println("Before Swapping");
         System.out.println("Value of num1 is :" + num1);
         System.out.println("Value of num2 is :" +num2);
        
         //add both the numbers and assign it to first
         num1 = num1 + num2;
         num2 = num1 - num2;
         num1 = num1 - num2;
        
         System.out.println("Before Swapping");
         System.out.println("Value of num1 is :" + num1);
         System.out.println("Value of num2 is :" +num2);
 }

 
}
/* Output :
Before Swapping
Value of num1 is :10
Value of num2 is :20
After Swapping
Value of num1 is :20
Value of num2 is :10*/

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...