w3resource

PHP Exercises: Compute the sum of the three given integers. However, if any of the values is in the range 10..20 inclusive then that value counts as 0, except 13 and 17

PHP Basic Algorithm: Exercise-56 with Solution

Write a PHP program to compute the sum of the three given integers. However, if any of the values is in the range 10..20 inclusive then that value counts as 0, except 13 and 17.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes three parameters and returns the sum of fixed numbers
function test($x, $y, $z)
{
    // Call the 'fix_num' function on each input parameter and return the sum of fixed numbers
    return fix_num($x) + fix_num($y) + fix_num($z);
}

// Define a function named 'fix_num' that takes a number as input and returns a fixed number based on conditions
function fix_num($n)
{
    // Check if $n is between 10 and 13 or between 17 and 21 (exclusive)
    // If true, return 0; otherwise, return the original number
    return (($n < 13 && $n > 9) || ($n > 17 && $n < 21)) ? 0 : $n;
}

// Test the 'test' function with different input values and display the results
echo (test(4, 5, 7))."\n";
echo (test(7, 4, 12))."\n";
echo (test(10, 13, 12))."\n";
echo (test(17, 12, 18))."\n";
?>

Sample Output:

16
11
13
17

Flowchart:

Flowchart: Compute the sum of the three given integers. However, if any of the values is in the range 10..20 inclusive then that value counts as 0, except 13 and 17.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to compute the sum of the three integers. If one of the values is 13 then do not count it and its right towards the sum.
Next: Write a PHP program to check two given integers and return the value whichever value is nearest to 13 without going over. Return 0 if both numbers go over.

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.