Swapping two variables without using third variable


<!–Swapping two number without using third variable–>
<?php
$a = 3;
$b = 2;

echo “Before swapping a and b : $a, $b”.”<br/>”;

$a = $a+$b; // value of $a now is 5
$b = $a-$b; // value of $b now is 3
$a = $a-$b; // value of $a now is 2

echo “After swapping a and b : $a, $b”;

?>

This is one of the simple logic questions asking in the freshers interview.
Usually we used to swap two variables using the third temporary variable.
Here we assigned $a itself a temporary varible. So that we don’t need third one.
Here what the logic is assign $a’s or $b’s value to one place.
ie) $a=3; $b=2; $a= $a+$b;

Now $a is 5 (logic goes here)

Using the $a value 5, we can start swapping $a & $b in the above manner.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s