w3resource

PHP Exercises: Check whether two given integers are in the range 40..50 inclusive

PHP Basic Algorithm: Exercise-20 with Solution

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.

Sample Solution:

PHP Code :

<?php
// Define a function that checks if a point is within one of two rectangular regions
function test($x, $y) 
{
    // Check if the point is within the first rectangular region
    $condition1 = ($x >= 40 && $x <= 50 && $y >= 40 && $y <= 50);
    
    // Check if the point is within the second rectangular region
    $condition2 = ($x >= 50 && $x <= 60 && $y >= 50 && $y <= 60);
    
    // Return true if the point is within either region, otherwise false
    return $condition1 || $condition2;
}

// Test the function with different sets of coordinates
var_dump(test(78, 95));
var_dump(test(25, 35));
var_dump(test(40, 50));
var_dump(test(55, 60));
?>

Explanation:

  • Function Definition:
    • The test function takes two parameters, $x and $y, representing the coordinates of a point.
  • Region Checks:
    • First Rectangle (condition1): Checks if the point is within the rectangle bounded by x = 40 to 50 and y = 40 to 50.
    • Second Rectangle (condition2): Checks if the point is within the rectangle bounded by x = 50 to 60 and y = 50 to 60.
  • Return Value:
    • The function returns true if the point lies within either of the two rectangles; otherwise, it returns false.
  • Function Calls and Results:
    • First Call: test(78, 95) returns false as (78, 95) is outside both regions.
    • Second Call: test(25, 35) returns false as (25, 35) is outside both regions.
    • Third Call: test(40, 50) returns true as (40, 50) is within the first region.
    • Fourth Call: test(55, 60) returns true as (55, 60) is within the second region.

Output:

bool(false)
bool(false)
bool(true)
bool(true)

Flowchart:

Flowchart: Check whether two given integers are in the range 40..50 inclusive.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: 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.
Next: Write a PHP program to find the larger value from two positive integer values that is in the range 20..30 inclusive, or return 0 if neither is in that range.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-20.php