w3resource

PHP Exercises: Check which number nearest to the value 100 among two given integers

PHP Basic Algorithm: Exercise-19 with Solution

Write a PHP program to check which number nearest to the value 100 among two given integers. Return 0 if the two numbers are equal.

Sample Solution:

PHP Code :

<?php
// Define a function that takes two parameters and returns the one closer to the value 100
function test($x, $y) 
{
   // Define the target value
   $n = 100;
   
   // Calculate the absolute difference between $x and $n
   $val = abs($x - $n);
   
   // Calculate the absolute difference between $y and $n
   $val2 = abs($y - $n);
   
   // Compare the absolute differences and return the value closer to $n
   return $val == $val2 ? 0 : ($val < $val2 ? $x : $y);
}

// Test the function with different sets of values
echo test(78, 95)."\n";
echo test(95, 95)."\n";
echo test(99, 70)."\n";
?>

Sample Output:

95
0
99

Pictorial Presentation:

PHP Basic Algorithm Exercises: Check which number nearest to the value 100 among two given integers.
PHP Basic Algorithm Exercises: Check which number nearest to the value 100 among two given integers.

Flowchart:

Flowchart: Check which number nearest to the value 100 among two given integers.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check the largest number among three given integers.
Next: Write a PHP program to check whether two given integers are in the range 40..50 inclusive, or they are both in the range 50..60 inclusive.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.