PHP Exercises: Compute the sum of the two given integers. If one of the given integer value is in the range 10..20 inclusive return 18
PHP Basic Algorithm: Exercise-44 with Solution
Write a PHP program to compute the sum of the two given integers. If one of the given integer value is in the range 10..20 inclusive return 18.
Sample Solution:
PHP Code :
<?php
// Define a function that checks if either $x or $y is in the range [10, 20], and returns 18 if true, otherwise returns the sum of $x and $y
function test($x, $y)
{
// Check if $x is in the range [10, 20] OR $y is in the range [10, 20]
// If true, return 18; otherwise, return the sum of $x and $y
return ($x >= 10 && $x <= 20) || ($y >= 10 && $y <= 20) ? 18 : $x + $y;
}
// Test the function with different pairs of numbers
echo test(3, 7)."\n";
echo test(10, 11)."\n";
echo test(10, 20)."\n";
echo test(21, 220)."\n";
?>
Explanation:
- Function Definition:
- The test function checks if either of the numbers $x or $y is within the range [10, 20].
- Condition Checked:
- The function evaluates whether:
- $x is between 10 and 20 (inclusive) OR
- $y is between 10 and 20 (inclusive).
- If either condition is true, the function returns 18.
- If both conditions are false, it returns the sum of $x and $y.
Output:
10 18 18 241
Pictorial Presentation:
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check if a given number is within 2 of a multiple of 10.
Next: 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.
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-44.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics