Write a program to swap 2 numbers without using the temporary variable

The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.

C/C++

#include <stdio.h>
int main()
{
int x = 10, y = 5;

// Code to swap ‘x’ and ‘y’
x = x + y; // x now becomes 15
y = x – y; // y becomes 10
x = x – y; // x becomes 5

printf(“After Swapping: x = %d, y = %d”, x, y);

return 0;
}

Java

// Program to swap two numbers without
// using temporary variable
import java.*;

class PrepInsta {

public static void main(String a[])
{
int x = 10;
int y = 5;
x = x + y;
y = x – y;
x = x – y;
System.out.println(“After swaping:”
+ ” x = ” + x + “, y = ” + y);
}
}

Python

x = 10
y = 5

# Code to swap ‘x’ and ‘y’

# x now becomes 15
x = x + y

# y becomes 10
y = x – y

# x becomes 5
x = x – y
print(“After Swapping: x =”,x ,” y =”, y);