Swap two Numbers without using third variable Algorithm in Java

[4746 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

For eg.
Input: a=24 b=36
Output: a=36 b=24

  1. Swapping Using Arithmetic Operators
  2. Algorithm Or Pseudocode to Swap two Number without using Third or Temporary 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); } }

    Consider a=10 and b=20. In this program, the first variable is first added to the second variable and stored in the first variable. Then the second variable is subtracted from the first variable and stored in the second variable. Lastly, the value of the 2nd variable is subtracted from 1st and stored in the first variable. This is how the values of one variable get swapped to another and vice versa, i.e. a becomes 20 and b becomes 10.

  3. Swapping Using Bitwise XOR
  4. Algorithm 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); } }
                 



Clear Any Java Interview by Reading our Ebook Once.


Can you clear Java Interview?




Comments










Search Anything:

Sponsored Deals ends in





Technical Quizzes Specially For You:

Search Tags

    Write a Java program to Swap two numbers without using a temporary variable

    swap two numbers without using temporary variable

    swapping without third variable

    swap 2 numbers using bitwise XOR operators