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

Comments

Popular posts from this blog

Develop an Android application to display “Hello World!” on screen

Program to design an applet which draws a circle (having color BLUE) inside a triangle (having color YELLOW)

Build a Simple Android App to Display Student Details