This is a program using which you can swap two numbers without using a third variable.
This program is crafted using Java Language.
public static void main (String args)
Scanner s= new Scanner(System.in);
System.out.print("Enter The Value Of A: ");
System.out.print("Enter The Value Of B: ");
System.out.println("Swapped, a: "+a+", b: "+b);
This program swaps the two number without using a third value. Let say the value of a is 10 and b is 5.
First Calculation: a=a+b, So a=10+5=15.
Second Calculation: b=a-b, So b=15-5=10.
Third Calculation: a=a-b, So a=15-10=5.
Now the values of both a and b have successfully changed. Instead of add and sub, you can alternatively use mul and div.
The Complexity is of order 1, O(1).
Latest posts by Bikash Panda (see all)
- OSMC on Raspberry PI with Setup and Control using Android App - July 7, 2017
- DHT12 Interfacing with Raspberry Pi using Pi4J - June 19, 2017
- Send data using MQTT from Raspberry Pi with JAVA - June 12, 2017