Swapping of two numbers
In this program, we will take two numbers get them swapped using the swap logic.
Let take the value of a = 10 and b = 20 after swapping of two numbers we will get a =20 and b = 10
Steps to write Swapping of two numbers are:
Step 1: Get two values from users
Step 2: Use the swap logic to swap the numbers
Step 3: Display the output of the swapped numbers
Class swap
{
public static void main(String args[]) // Main method
{
int num1, num2; // We can assign only integer values to num1,num2
num1= Integer.parseInt(args[0]); // It will take the Integer value
num2= Integer.parseInt(args[1]); // It will take the Integer value
System.out.println(“ Before swapping”);
System.out.println(“ Number 1:” +num1);
System.out.println(““ Number 2:” +num2”);
// Swap logic
num1= num1+num2;
num2= num1-num2;
num1= num1-num2;
System.out.println(“After swapping”);
System.out.println(“ Number 1:” +num1); // Displaying the no after the swapping
System.out.println(““ Number 2:” +num2”);
}
}
So now let explain the program
Let assign integer value to num1 and num2
num1 = 10
num2 = 20
Now let apply the swap logic given in the program
Step1: num1 = num1 + num2
num1 = 10 +20
So now the num1 value will become 30
num1=30
Step2: num2 = num1 - num2
num2 = 30 – 20
So now the value of num2 is 10
num2= 10
Step3: num1 = num1 – num2
num1 = 30 – 10
Now the value of num1 is 20
num1 = 20
So after applying the swapping logic in 3 steps we get our values of num1 and num2 swapped
Before swapping values were
num1=10
num2 =20
After swapping values are
num1=20
num2 =10