Computer Science, asked by mahibisht01, 1 year ago

write a program to swap two values.​

Answers

Answered by rakeshchennupati143
2

Program:

import java.io.*;

import java.util.*;

public class Main{

     public static void main(String args[]){

           Scanner sc = new Scanner(System.in);

           System.out.println("Enter Two Variables To Swap Each Other : ");

           int num1 = sc.nextInt();

           int num2 = sc.nextInt();

           System.out.println("Before swap num1 = "+num1+", num2 = "+num2);

           num1 = num1 + num2;

           num2 = num1 - num2;

           num2 = num1 - num2;

           System.out.println("After swap num1 = "+num1+", num2 = "+num2);

     }

}

Output:

Enter Two Variables To Swap Each Other :

5

10

Before swap num1 = 5, num2 = 10

Before swap num1 = 10, num2 = 5

Explanation:

  1. i swapped without using any third variable in the code
  2. i took 2 number as num1 and num2
  3. in the logic first i added num1 and num2 and stored it in num1
  4. then i subtracted num1 with num2 and stored it in num2 so that num2 will get num1 value because in programming recent value is considerec
  5. then i subtracted num1 with num2 and stored it in num1, then num1 will have the value of num2
  6. and i printer them

----Hope This will help you   :)

Similar questions