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.

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);
C:\>javac SwappingWithoutThirdVar.java
C:\>java SwappingWithoutThirdVar
Before swapping : a = 75 b = 45
After swapping : a = 45 b = 75


Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet