w3resource

PHP Exercises: 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


55. Sum Excluding 13 and Right Side

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.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes three parameters and returns a value based on certain conditions
function test($x, $y, $z)
{
    // Check if $x is equal to 13; if true, return 0
    if ($x == 13) return 0;
    
    // Check if $y is equal to 13; if true, return $x
    if ($y == 13) return $x;
    
    // Check if $z is equal to 13; if true, return the sum of $x and $y
    if ($z == 13) return $x + $y;
    
    // If none of the above conditions are met, return the sum of $x, $y, and $z
    return $x + $y + $z;
}

// 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(13, 12, 18))."\n";
?>

Explanation:

  • Function Definition:
    • The test function takes three parameters: $x, $y, and $z, and returns a value based on specific conditions related to the value 13.
  • Conditions:
    • If $x is 13: The function returns 0 immediately, disregarding the other values.
    • If $y is 13: The function returns only the value of $x, ignoring $z.
    • If $z is 13: The function returns the sum of $x and $y, ignoring $z.
    • None of the Above: If none of the parameters is 13, it returns the sum of all three values: $x + $y + $z.

Output:

16
23
10
0

Flowchart:

Flowchart: 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.

For more Practice: Solve these Related Problems:

  • Write a PHP script to add three integers but ignore any number and the numbers to its right once 13 is encountered in the input.
  • Write a PHP function to traverse three numbers and conditionally sum only those before encountering 13.
  • Write a PHP program to compute a conditional sum where encountering a 13 cancels out subsequent values.
  • Write a PHP script to simulate a three-number addition that stops adding further inputs if 13 appears.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Write a PHP program to compute the sum of three given integers. If the two values are same return the third value.
Next: 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.

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.