Swap number without using third variable.
This is simple java code which explains how to swap number without using third
variable . This only example to use mathematical tricks to solve the problem.
public class SwapNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1 = 20;
int num2 = 90;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
//add both the numbers and assign it to first
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
}
}
Before Swapping
Value of num1 is :20
Value of num2 is :90
Before Swapping
Value of num1 is :90
Value of num2 is :20
Swap number without using third variable.
Reviewed by Mukesh Jha
on
3:50 AM
Rating:
No comments:
Add your comment