Java Program to Swap two Numbers without using third variable

(148 Views)


Swap two Number Variables without using extra temp variable

Problem Statement

Write a Java Program to Swap two numbers without using a Third Variable

OR

Write a Java program to Swap two numbers without using temporary variable
For eg.
Input: a=24 b=36
Output: a=36 b=24

Method 1 (Swapping Using Arithmetic Operators)

FlowChart Or Pseudocode to Swap two Number without using Third or Temp variable Using Arithmetic Operators
FlowChart Or Pseudocode to Swap two Number without using Third or Temp variable in Java Using Arithmetic Operators
swapWithoutVariable.java
import java.util.Scanner; public class swapWithoutVariable{ public static void main(String[] args){ int a,b; Scanner sc=new Scanner(System.in); a=sc.nextInt(); b=sc.nextInt(); a=a+b; b=a-b; a=a-b; System.out.println("a= "+a); System.out.println("b= "+b); } }

Method 2 (Swapping Using Bitwise XOR)

FlowChart Or Pseudocode to Swap two Number without using Third or Temp variable Using Bitwise XOR
FlowChart Or Pseudocode to Swap two Number without using Third or Temp variable in Java Using Bitwise XOR
swapWithoutVariable2.java
import java.util.Scanner; public class swapWithoutVariable2{ public static void main(String[] args){ int a,b; Scanner sc=new Scanner(System.in); a=sc.nextInt(); b=sc.nextInt(); a=a^b; b=a^b; a=a^b; System.out.println("a= "+a); System.out.println("b= "+b); } }

Solution Worked 6 UpvotesUpvote

        

Solution Didn't Worked 1 DownvotesDownvote



Comments



Search