Popular Posts

July 16, 2024

Swap Two Numbers Without Using Temporary Variable Java Program

 

Swap Two Numbers Without Using Temporary Variable Java Program

Java Program:

How to swap two numbers without using temporary variable?

Description:

Write a program to swap or exchange two numbers. You should
not use any temporary or third variable to swap.

Code:

package com.java2novice.algos;

public class MySwapingTwoNumbers {

    public static void main(String a[]){
        int x = 10;
        int y = 20;
        System.out.println("Before swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
        x = x+y;
        y=x-y;
        x=x-y;
        System.out.println("After swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
    }
}

Output:

Before swap:
x value: 10
y value: 20
After swap:
x value: 20
y value: 10

Here's a simple Java program to swap two numbers without using a temporary variable:

import java.util.Scanner;


public class SwapNumbers {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        

        System.out.print("Enter first number: ");

        int a = scanner.nextInt();

        

        System.out.print("Enter second number: ");

        int b = scanner.nextInt();

        

        // Swapping using arithmetic operations

        a = a + b; // Step 1: Sum the two numbers

        b = a - b; // Step 2: Subtract the new value of a (sum) by b to get the original a

        a = a - b; // Step 3: Subtract the new value of b (original a) from the sum to get the original b

        

        System.out.println("After swapping:");

        System.out.println("First number: " + a);

        System.out.println("Second number: " + b);

        

        scanner.close();

    }

}

Explanation:

  1. Input: The program prompts the user to enter two integers.
  2. Swapping Logic:
    • First, it adds both numbers and stores the result in a.
    • Then, it subtracts b from the new a, which gives the original value of a, and stores it in b.
    • Finally, it subtracts the new b (original a) from the new a (sum), resulting in the original value of b and stores it back in a.
  3. Output: The program prints the values of the two numbers after swapping.

Note:

This method works for integer values, but be careful with potential overflow when dealing with very large integers.

No comments:
Write comments