Tuesday, 22 November 2016

Swap numbers without using third variable

Swapping is the exchanging the values of variables. For example, if a=25 and b=37 then after swapping the values are a=37 and b=25. In this program, we swap the two variables without using the third variable. The logic for that is given in program.


PROGRAM
class SwappingWithoutThirdVar {

 public static void main(String[] args) {
  
  int a = 75, b=45, temp;
  
  System.out.println("Before swapping : a = "+a+" b = "+b);
  
  b = a + b;
  a = b - a;
  b = b - a;
  
  System.out.println("After swapping : a = "+a+" b = "+b);
 }
}
OUTPUT
C:\>javac SwappingWithoutThirdVar.java
C:\>java SwappingWithoutThirdVar
Before swapping : a = 75 b = 45
After swapping : a = 45 b = 75

No comments:

Post a Comment