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:
- Input: The program prompts the user to enter two integers.
- Swapping Logic:
- First, it adds both numbers and stores the result in
a
. - Then, it subtracts
b
from the newa
, which gives the original value ofa
, and stores it inb
. - Finally, it subtracts the new
b
(originala
) from the newa
(sum), resulting in the original value ofb
and stores it back ina
.
- First, it adds both numbers and stores the result in
- 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