PHP Exercises: Compute the sum of three given integers. If the two values are same return the third value
PHP Basic Algorithm: Exercise-54 with Solution
Write a PHP program to compute the sum of three given integers. If the two values are same return the third value.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that takes three parameters and returns a value based on certain conditions
function test($x, $y, $z)
{
// Check if all three parameters are equal; if true, return 0
if ($x == $y && $y == $z) return 0;
// Check if $x is equal to $y; if true, return $z
if ($x == $y) return $z;
// Check if $x is equal to $z; if true, return $y
if ($x == $z) return $y;
// Check if $y is equal to $z; if true, return $x
if ($y == $z) return $x;
// If none of the above conditions are met, return the sum of $x, $y, and $z
return $x + $y + $z;
}
// Test the 'test' function with different input values and display the results
echo (test(4, 5, 7))."\n";
echo (test(7, 4, 12))."\n";
echo (test(10, 10, 12))."\n";
echo (test(12, 12, 18))."\n";
?>
Explanation:
- Function Definition:
- The test function takes three parameters: $x, $y, and $z. Based on various conditions, it returns a specific value.
- Conditions:
- All Equal: If all three parameters ($x, $y, and $z) are equal, the function returns 0.
- Two Equal (Returning Third):
- If $x and $y are equal, it returns $z.
- If $x and $z are equal, it returns $y.
- If $y and $z are equal, it returns $x.
- None of the Above: If none of the values are equal, it returns the sum of $x, $y, and $z.
Output:
16 23 12 18
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to compute the sum of two given non-negative integers x and y as long as the sum has the same number of digits as x. If the sum has more digits than x then return x without y.
Next: Write a PHP program to compute the sum of the three integers. If one of the values is 13 then do not count it and its right towards the sum.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-54.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics