Introduction
Swapping the values of two variables without using a temporary variable is a common programming challenge. This tutorial will guide you through creating a Python program that accomplishes this using simple arithmetic operations.
Problem Statement
Create a Python program that:
- Takes two variables and swaps their values without using a temporary variable.
Example:
- Input:
x = 15
,y = 25
- Output:
After swapping: x = 25, y = 15
Solution Steps
- Initialize Two Variables: Start by assigning values to two variables.
- Swap the Variables Using Arithmetic Operations: Use addition and subtraction to swap the values.
- Display the Result: Use the
print()
function to display the values of the variables after swapping.
Python Program
# Python Program to Swap Two Variables Without a Temporary Variable
# Author: https://www.javaguides.net/
# Step 1: Initialize two variables
x = 15
y = 25
# Step 2: Swap the variables using arithmetic operations
x = x + y # x now becomes 40
y = x - y # y now becomes 15 (original value of x)
x = x - y # x now becomes 25 (original value of y)
# Step 3: Display the result
print(f"After swapping: x = {x}, y = {y}")
Explanation
Step 1: Initialize Two Variables
- Assign initial values to two variables,
x
andy
. In this example,x = 15
andy = 25
.
Step 2: Swap the Variables Using Arithmetic Operations
- The values of
x
andy
are swapped using arithmetic operations:- First, add the two variables and store the result in
x
. Now,x
holds the sum of both original values. - Subtract the new value of
x
byy
to assign the original value ofx
toy
. - Finally, subtract the new value of
y
fromx
to assign the original value ofy
tox
.
- First, add the two variables and store the result in
Step 3: Display the Result
- The
print()
function is used to display the values ofx
andy
after swapping. Thef-string
format is used to directly include the variable values within the string.
Output Example
Example:
After swapping: x = 25, y = 15
Conclusion
This Python program demonstrates how to swap the values of two variables without using a temporary variable by utilizing arithmetic operations. This method is efficient and avoids the need for additional memory allocation, making it a valuable technique in resource-constrained environments.