Swap Magic
Do you think it is possible to swap values between two variables without using a third temporary variable? What? No? Yes? Well, the answer is...YES. Take a look at the code and don't forget to vote!
AI
AI Summary: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.
Source Code
/*
Swap Magic
Swaps values between two variables without using a third temporary variable
Programmer: Fazle Arefin
*/
public class SwapMagic {
public static void main(String args[]) {
// declare and initialize two variables
int a = 10;
int b = 20;
System.out.println("Before swapping a = " + a + " and b = " + b);
a = a + b;
b = a - b;
a= a - b;
/*
instead of + and - you can use * and / respectively
a = a * b;
b = a / b;
a= a / b;
instead of + and - or * and / you can use the XOR operator ^
but this restricts you to only swapping integers
a = a ^ b;
b = a ^ b;
a= a ^ b;
*/
System.out.println("Before swapping a = " + a + " and b = " + b);
}
}
Original Comments (3)
Recovered from Wayback Machine