Swap Three Integers Without Temporary Variable in Java

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 Java.

What’s The Approach?

  • Let us consider a, b & c to 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 a from b+c and assign this new value to b. i.e, 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 . i.e, c = a - (b+c) this way we’ll store the value of variable b into variable c.
  • Python Program to Swap Two Numbers
  • For this final time, again we will subtract the value of a from b+c and assign this new value to a . i.e,  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 & c.

Also Read: Print Prime Numbers Between Two Integers in Java

Java Program To Swap Three Integers Without Temporary Variable

 

Input:

a = 10, b = 20, c = 30

Output:

a = 30, b = 10, c = 20

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published.