Swap two numbers 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 using the third variable. The third variable is a temporary variable which is used stored a value temporary. First we save the value of 'a' in 'temp', then b's value is store in 'a' and finally store the value of 'temp' in 'b'.

PROGRAM
class SwappingUsingThirdVar {

 public static void main(String[] args) {

  int a = 10, b=20, temp;
  
  System.out.println("Before swapping : a = " + a + " b = " + b);
  
  temp = a;
  a = b;
  b = temp;
  
  System.out.println("After swapping : a = " + a + " b = " + b);
 }
}
OUTPUT
C:\>javac SwappingUsingThirdVar.java
C:\>java SwappingUsingThirdVar
Before swapping : a = 10 b = 20
After swapping : a = 20 b = 10

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 input age from user and throw user-defined exception if entered age is negative