w3resource

PHP Exercises: Get the absolute difference between n and 51

PHP Basic Algorithm: Exercise-2 with Solution

Write a PHP program to get the absolute difference between n and 51. If n is greater than 51 return triple the absolute difference.

Sample Solution:

PHP Code :

<?php
// Define a function named "test" that takes a parameter $n
function test($n) 
{
    // Declare a variable $x and assign it the value 51
    $x = 51;

    // Check if $n is greater than $x
    if ($n > $x)
    {
        // If true, return the result of multiplying the difference between $n and $x by 3
        return ($n - $x) * 3;
    }

    // If false, return the difference between $x and $n
    return $x - $n;
}

// Call the test function with argument 53 and echo the result
echo test(53) . "\n";

// Call the test function with argument 30 and echo the result
echo test(30) . "\n";

// Call the test function with argument 51 and echo the result
echo test(51) . "\n";
?>

Sample Output:

6
21
0

Visual Presentation:

PHP Basic Algorithm Exercises: Get the absolute difference between n and 51

Flowchart:

Flowchart: Get the absolute difference between n and 51

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to compute the sum of the two given integer values. If the two values are the same, then returns triple their sum.
Next: Write a PHP program to check two given integers, and return true if one of them is 30 or if their sum is 30.

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.