How to swap two numbers without using a temporary variable in C/C++/Java/Python
In C :
We input two numbers and perform arithmetic operations of multiplication and division and the numbers are swapped
#include <stdio.h>
int main()
{ int x,y;
printf("enter a number x");
scanf("%d", &x);
printf("enter a number y");
scanf("%d",&y);
x = x * y;
y = x / y;
x = x / y;
printf("After Swapping: x = %d, y = %d", x, y);
return 0;
}
The Output:
enter a number x32
enter a number y56
After Swapping: x = 56, y = 32
In C++:
We input two numbers by default and perform arithmetic operations of multiplication and division and the numbers are swapped.
#include <bits/stdc++.h>
using namespace std;
int main()
int x = 8, y = 4;
x = x * y;
y = x / y;
x = x / y;
cout << "After Swapping: x =" << x << ", y=" << y;
}
The output:
After swapping x=4 , y=8
In python:
We input two numbers from the user and perform arithmetic operations of multiplication and division and the numbers are swapped
x=int(input("enter a number"))
y=int(input("enter a number"))
x = x * y
y = x // y;
x = x // y;
print("After Swapping: x =",
x, " y =", y);
The output:
enter a number45
enter a number78
After Swapping: x = 78 y = 45
In Java:
We input two numbers from the user and perform arithmetic operations of multiplication and division and the numbers are swapped.
import java.io.*;
import java.util.Scanner;
class GFG {
public static void main(String[] args)
{ Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
int x = scan.nextInt();
System.out.print("enter any number :");
int y = scan.nextInt();
scan.close();
x = x * y;
y = x / y;
x = x / y;
System.out.println("After swapping:"
+ " x = " + x + ", y = " + y);
}
}
The Output:
Enter any number: 43
enter any number:67
After swapping: x = 67, y = 43
Time and Space Complexity
Time complexity– o(1), it will not take time for the code to execute.
Auxiliary space – o(1)