PHP Exercises: Find the larger from two given integers
PHP Basic Algorithm: Exercise-51 with Solution
Write a PHP program to find the larger from two given integers. However if the two integers have the same remainder when divided by 7, then the return the smaller integer. If the two integers are the same, return 0.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that compares two numbers and returns the result
function test($x, $y)
{
// Check if $x is equal to $y
if ($x == $y)
{
// Return 0 if $x is equal to $y
return 0;
}
// Check if $x is not equal to $y and satisfies another condition
else if (($x % 7 == $y % 7 && $x < $y) || $x > $y)
{
// Return $x if the condition is met
return $x;
}
// If none of the above conditions are met
else
{
// Return $y
return $y;
}
}
// Test the 'test' function with different input values and display the results
echo test(11, 21)."\n";
echo test(11, 20)."\n";
echo test(10, 10)."\n";
?>
Explanation:
- Function Definition:
- The function test compares two numbers, $x and $y, and returns a result based on specific conditions.
- Conditions and Logic:
- Condition 1: If $x is equal to $y, it returns 0.
- Condition 2: If $x is not equal to $y, it checks:
- If $x and $y have the same remainder when divided by 7 ($x % 7 == $y % 7) and $x is less than $y, or if $x is greater than $y, then it returns $x.
- Condition 3: If none of the above conditions are met, it returns $y.
Output:
21 20 0
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check three given integers and return true if one of them is 20 or more less than one of the others.
Next: Write a PHP program to check two given integers, each in the range 10..99. Return true if a digit appears in both numbers, such as the 3 in 13 and 33.
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-51.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics