PHP Exercises: Check if it is possible to add two integers to get the third integer from three given integers
PHP Basic Algorithm: Exercise-46 with Solution
Write a PHP program to check if it is possible to add two integers to get the third integer from three given integers.
Sample Solution:
PHP Code :
<?php
// Define a function that checks if any two numbers add up to the third number
function test($x, $y, $z)
{
// Check if $x is equal to the sum of $y and $z
// OR if $y is equal to the sum of $x and $z
// OR if $z is equal to the sum of $x and $y
return $x == $y + $z || $y == $x + $z || $z == $x + $y;
}
// Test the function with different sets of numbers
var_dump(test(1, 2, 3))."\n";
var_dump(test(4, 5, 6))."\n";
var_dump(test(-1, 1, 0))."\n";
?>
Explanation:
- Function Definition:
- The function test checks if any two numbers from the inputs $x, $y, and $z add up to the third number.
- Conditions Checked:
- Condition 1: Checks if $x is equal to the sum of $y and $z.
- Condition 2: Checks if $y is equal to the sum of $x and $z.
- Condition 3: Checks if $z is equal to the sum of $x and $y.
- If any of these conditions are true, the function returns true; otherwise, it returns false.
Output:
bool(true) bool(false) bool(true)
Visual Presentation:
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check whether a given string starts with "F" or ends with "B". If the string starts with "F" return "Fizz" and return "Buzz" if it ends with "B" If the string starts with "F" and ends with "B" return "FizzBuzz". In other cases return the original string.
Next: Write a PHP program to check if y is greater than x, and z is greater than y from three given integers x,y,z.
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://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-46.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics