PHP Exercises: Check if a given number is within 2 of a multiple of 10
PHP Basic Algorithm: Exercise-43 with Solution
Write a PHP program to check if a given number is within 2 of a multiple of 10.
Sample Solution:
PHP Code :
<?php
// Define a function that checks if the last digit of a number is less than or equal to 2 OR greater than or equal to 8
function test($n)
{
// Check if the remainder of $n divided by 10 is less than or equal to 2 OR greater than or equal to 8
return $n % 10 <= 2 || $n % 10 >= 8;
}
// Test the function with different values
var_dump(test(3));
var_dump(test(7));
var_dump(test(8));
var_dump(test(21));
?>
Explanation:
- Function Definition:
- The test function checks if the last digit of a given number $n is within a specific range.
- Condition Checked:
- The function evaluates whether the last digit of $n:
- Is less than or equal to 2 (i.e., $n % 10 <= 2), OR
- Is greater than or equal to 8 (i.e., $n % 10 >= 8).
- This is done by checking the remainder when $n is divided by 10, which gives the last digit of $n.
Output:
bool(false) bool(false) bool(true) bool(true)
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check if a given non-negative given number is a multiple of 3 or 7, but not both.
Next: 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.
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-43.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics