Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Swap two variables in one line in C/C++, Python, PHP and Java
In this tutorial, we are going to learn how to swap two variables in different languages. Swapping means interchanging the values of two variables. Let's see an example.
Input
a = 3 b = 5
Output
a = 5 b = 3
Let's see how to achieve this in different programming languages.
Python
We can swap variables with one line of code in Python using tuple unpacking −
Example
# initializing the variables
a, b = 3, 5
# printing before swapping
print("Before swapping:-", a, b)
# swapping
a, b = b, a
# printing after swapping
print("After swapping:-", a, b)
Output
Before swapping:- 3 5 After swapping:- 5 3
XOR Method for C/C++, PHP, and Java
In languages like C/C++, PHP, and Java, we can use the XOR operator to swap variables in one line. The XOR method works through these steps −
- Perform XOR operation on two variables and assign the result to the first variable
- Perform XOR operation and assign the result to the second variable
- Perform XOR operation and assign the result to the first variable again
- The variables will be swapped
C/C++
Example
#include <stdio.h>
int main() {
int a = 3, b = 5;
printf("Before Swapping:- %d %d\n", a, b);
(a ^= b), (b ^= a), (a ^= b);
printf("After Swapping:- %d %d\n", a, b);
return 0;
}
Output
Before Swapping:- 3 5 After Swapping:- 5 3
Java
Example
class Swap {
public static void main (String[] args) {
int a = 3, b = 5;
System.out.println("Before Swapping:- " + a + " " + b);
a = a ^ b ^ (b = a);
System.out.println("After Swapping:- " + a + " " + b);
}
}
Output
Before Swapping:- 3 5 After Swapping:- 5 3
PHP
Example
<?php
$a = 5;
$b = 10;
echo "Before Swapping:- $a $b\n";
($a ^= $b), ($b ^= $a), ($a ^= $b);
echo "After Swapping:- $a $b\n";
?>
Output
Before Swapping:- 5 10 After Swapping:- 10 5
Conclusion
Python offers the most elegant solution with tuple unpacking, while other languages can achieve one−line swapping using the XOR operator. The XOR method works efficiently for integer values without requiring temporary variables.
Advertisements
