Program to swap two numbers
Input:
Enter the value of X and Y
num1=10
num2=20
Before swapping: 10 20
Output:
num1=20
num2=10
After swapping: 20 10
Solution:
Language Used: Java
Approach 1:
swap two numbers using the third variable
import java.util.Scanner;
public class Swap {
public static void main(String[] args) {
Scanner s = new Scanner(System.in) ;
System.out.println("Enter first number");
int num1 = s.nextInt() ;
System.out.println("Enter second number");
int num2 = s.nextInt() ;
System.out.println("Before swapping: "+num1+" "+num2);
logic-1 - swap two numbers using third variable
int temp;
temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping: "+num1+" "+ num2);
}
}
Approach 2:
swap two numbers without using a third variable using + and -
import java.util.Scanner;
public class Swap {
public static void main(String[] args) {
Scanner s = new Scanner(System.in) ;
System.out.println("Enter first number");
int num1 = s.nextInt() ;
System.out.println("Enter second number");
int num2 = s.nextInt() ;
System.out.println("Before swapping: "+num1+" "+num2);
num1=num1+num2 ;
num2=num1-num2 ;
num1=num1-num2 ;
System.out.println("After swapping: "+num1+" "+ num2);
}
}
Approach 3:
swap two numbers using * and /
import java.util.Scanner;
public class Swap {
public static void main(String[] args) {
Scanner s = new Scanner(System.in) ;
System.out.println("Enter first number");
int num1 = s.nextInt() ;
System.out.println("Enter second number");
int num2 = s.nextInt() ;
System.out.println("Before swapping: "+num1+" "+num2);
num1=num1*num2 ;
num2=num1/num2 ;
num1=num1/num2 ;
System.out.println("After swapping: "+num1+" "+ num2);
}
}
Approach 4:
swap two numbers using bitwise X-OR
import java.util.Scanner;
public class Swap {
public static void main(String[] args) {
Scanner s = new Scanner(System.in) ;
System.out.println("Enter first number");
int num1 = s.nextInt() ;
System.out.println("Enter second number");
int num2 = s.nextInt() ;
System.out.println("Before swapping: "+num1+" "+num2);
num1=num1^num2 ;
num2=num1^num2 ;
num1=num1^num2 ;
System.out.println("After swapping: "+num1+" "+ num2);
}
}
Approach 5:
swap two numbers using a single statement
import java.util.Scanner;
public class Swap {
public static void main(String[] args) {
Scanner s = new Scanner(System.in) ;
System.out.println("Enter first number");
int num1 = s.nextInt() ;
System.out.println("Enter second number");
int num2 = s.nextInt() ;
System.out.println("Before swapping: "+num1+" "+num2);
num2=num1+num2-(num1=num2) ;
System.out.println("After swapping: "+num1+" "+ num2);
}
}