It’s quite amusing to see how different variations of solutions for the same questions are thereby different individuals. From pretty ancient times maths has played a very vital role in civilizations. Not to mention how everything around us revolves mathematically. Now programming is more or less similar to that. It’s the second version of maths where to solve real-world problems you need to apply real-world mathematical concepts. However, as we’re talking about maths, how about writing a program to swap Integers. So today let’s write a simple program to Swap Three Integers Without Temporary Variable in Python.
What’s The Approach?
- Let us consider
cto be the numbers we want to swap with each other. Now the catch is to do this without using a temporary variable.
- Firstly we’ll store the addition of these three variables in, one of the variables. That is,
a = a + b + c
- Now, we will subtract the value of
b+cand assign this new value to
b = a - (b+c)this way we’ll store the value of variable a into variable b.
- Again we will subtract the value of
a from b+c and assign this new value to
c = a - (b+c)
this way we’ll store the value of variable b into variable c.
- For this final time, again we will subtract the value of a from b+c and assign this new value to
a = a - (b+c)this way we’ll store the value of variable c into variable a.
- After the above three instructions finish executing we’ll print the values of a, b &
Python Program To Swap Three Integers Without Temporary Variable
a = 10, b = 20, c = 30
a = 30, b = 10, c = 20