Swap two numbers without using third variable


 

Swap two numbers without using third variable

In this section we are going to swap two variables without using the third variable.

In this section we are going to swap two variables without using the third variable.

Swap two numbers without using third variable

In this section we are going to swap two variables without using the third variable. For this, we have used input.nextInt() method of Scanner class for getting the integer type values from the command prompt. Instead of using temporary variable, we have done some arithmetic operations like we have added both the numbers and stored in the variable num1 then we have subtracted num2 from num1 and stored it into num2. After that, we have subtracted num2 from num1 and stored into num1. Now, we get the values that has been interchanged. To display the values on the command prompt use println() method and the swapped values will get displayed.

Here is the code:

import java.util.*;

class Swapping {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Enter Number 1: ");
		int num1 = input.nextInt();
		System.out.println("Enter Number 2: ");
		int num2 = input.nextInt();
		num1 = num1 + num2;
		num2 = num1 - num2;
		num1 = num1 - num2;
		System.out.println("After swapping, num1= " + num1 + " and num2= "
				+ num2);
	}
}

Output:

Enter Number 1:
20
Enter Number 2:
10
After swapping, num1=10 and num2=20

Ads