Featured Posts

Writing Website Scrapers in PHPWriting Website Scrapers in PHP This article discusses about how to write a website scraper using PHP for web site data extraction. The concepts taught can be applied and programmed in Java, C#, etc. Basically any language that has a...

Readmore

12 common programming mistakes to avoid12 common programming mistakes to avoid Programming is an art and science and like all art and science the only way to learn is from mistakes. I have made many... and I would like to share with you the mistakes that I have made over my journey...

Readmore

7 habits of highly effective freelance programmers7 habits of highly effective freelance programmers I have developed these based on my freelancing experience. Though I have discontinued freelancing, but would like to share my practices with you. These are basic practices and have been developed over...

Readmore

  • Prev
  • Next

How to swap 2 variables without temp variable

Posted on : 23-10-2007 | By : admin | In : Programming

5

Swapping 2 variables requires a third temp variable, this is how it is implemented with 3 variables (I have implemented this in PHP, the same logic can be used in any language):

<?php

$a = 5;
$b = 7;
$temp = $a;
$a = $b;
$b = $temp;

echo “$a : $b”;

?>




This is how we would do this using only 2 variables

<?php

$a = 5;
$b = 7;
$a = $a + $b; // $a becomes 12
$b = $a - $b; // $a becomes 5
$a = $a - $b; // $a becomes 7

echo “$a : $b”;

?>

Comments (5)

How to swap 2 variables without temp variable

for eg:-

Only problem is that it only works with numbers and not strings, arrays, or other variables types. The only way you can swap those efficiently is with the third variable.

nice!

Nice post, I like how you describe the solution in simple arithmetic terms; most textbooks use the bit-mask syntax, which I find less intuitive.

Of course, one could also say that this approach of swapping 2 integer variables without a third temporary variable is in fact using a third temporary variable composed of the unused higher-order bits of the 2 input variables. If the 2 variables used enough of the bits of their data-type, this swap would not work correctly. Exactly how big the values can get and still be accurately swapped this way I leave as an exercise for the reader. ;-)

It is very useful to all those programmers to improve logical thinking like this.

Write a comment

Enter this code