Swapping two numbers without using third variable [Method 2]
This is the Java programming code written in BlueJ which swaps the values of two numbers without using any third variable. This is the second method in which...
This is the Java programming code written in BlueJ which swaps the values of two numbers without using any third variable.
This is the second method in which we have used the concept of simple mathematical operations including addition and subtraction.
Method 1 of swapping two numbers using bitwise XOR operator and without using any third variable can be read from here: [Method 1]
Programming Code:
/**
* The class Swapping_Method2 takes 2 numbers as input and swaps their value without using any 3rd variable
* This is Method 2
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.util.Scanner;
class Swapping_Method2
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int a,b;
System.out.print("Enter the 1st no: ");
a=sc.nextInt();
System.out.print("Enter the 2nd no: ");
b=sc.nextInt();
System.out.println("-------------------------------");
System.out.println("The numbers before swapping are");
System.out.println("a = "+a);
System.out.println("b = "+b);
//Beginning of Swapping
a=a+b;
b=a-b;
a=a-b;
//End of Swapping
System.out.println("-------------------------------");
System.out.println("The numbers after swapping are");
System.out.println("a = "+a);
System.out.println("b = "+b);
}
}Output:
Enter the 1st no: 25
Enter the 2nd no: 13
——————————-
The numbers before swapping are
a = 25
b = 13
——————————-
The numbers after swapping are
a = 13
b = 25
Working:
Initially a=25 and b=13,
Step 1: a=a+b gives a=25+13
i.e. a=38
Step 2: b=a-b gives, b=38-13
i.e. b=25
Step 3: a=a-b gives, a=38-25
i.e. a=13
Hence, finally we have a=13 and b=25. [Swapping Done]
Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.