Swapping two numbers without using a third variable
This is a program using which you can swap two numbers without using a third variable.
This program is crafted using Java Language.
Description:
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).
This program is crafted using Java Language.
import java.util.Scanner; class swap { public static void main (String []args) { Scanner s= new Scanner(System.in); System.out.print("Enter The Value Of A: "); int a=s.nextInt(); System.out.print("Enter The Value Of B: "); int b=s.nextInt(); a=a+b; b=a-b; a=a-b; System.out.println("Swapped, a: "+a+", b: "+b); } }
Description:
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).
Comments
Post a Comment