How to write code for swap two numbers without using third variable in python
Python problem no:1
BY: DIBYANSHOO PANDEY
Python is a simple and object-oriented programming language, there is very simple to define the variable of the problem and describe the points of the problem, and easy to write the algorithm of problem.
Given two-variable a1 and a2. The task is to swap the values of both the variable without using the third variable.
Let's take the two variables and swap both numbers.
For Example:
X: 10
Y: 20
After swapping X and Y, We get :
X: 20
B: World
After swapping A and B, Wr get:
A: World
B: Hello
Method 1: Using the simple built-in method
Left = Right
Right = Left
x = 10
y = 20
print("Before swapping")
print("Value of x is: ",x,"and y",y)
x = y
y = x
print("After swapping")
print("Value of x is :",x,"and y",y)
Output:
Before swapping
Value of x is:10, and y 20
After swapping
Value of x is: 20, and y 10
Method 2:Using Adition and Subtraction method
Take the value of x and y to user
x = x+y
y = x-y
x = x-y
x = int(input("Enter the value of x"))
y = int(input("Enter the value of y"))
print("Before swapping")
print("Value of x :",x,"and y",y)
x = x+y
y = x-y
x =x-y
print("After swapping")
print("Value of x :",x,"and y",y)
Output:
Enter the value of x 10
Enter the value of y 20
Before swapping
Value of x: 10 and y 20
After swapping
Value of x: 20 and y 10
Thanks for reading this blog🙏
"Please Like the post and Subscribe my blogs, if you guys found worth reading this article, so share with your friends"🙏🙏
No comments:
Post a Comment