Given two variables a and b, swap two variables without using a third variable.
Method (Using Arithmetic Operators)
The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.
Method (Using Arithmetic Operators)
The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.
<?php
// PHP Program to swap two numbers without third variable
$a = 25;
$b = 19;
echo "a before swapping : ", $a;
echo "b before swapping : ", $b;
// code to swap numbers
$a = $a + $b; // a becomes 44 now
$b = $a - $b; // b becomes 25 now
$a = $a - $b; // a becomes 19 now
echo "a after swapping : ", $a;
echo "b after swapping : ", $b;
?>
OUTPUT:a before swapping : 25
b before swapping : 19
a after swapping 19
b after swapping 25
0 comments:
Post a Comment