write a program to swap two values.
Answers
Answered by
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:
- i swapped without using any third variable in the code
- i took 2 number as num1 and num2
- in the logic first i added num1 and num2 and stored it in num1
- 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
- then i subtracted num1 with num2 and stored it in num1, then num1 will have the value of num2
- and i printer them
----Hope This will help you :)
Similar questions
Economy,
6 months ago
Social Sciences,
6 months ago
Computer Science,
1 year ago
Chemistry,
1 year ago
Chemistry,
1 year ago