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";
?>

Explanation:

  • Function Definition:
    • A function named test is defined with a single parameter $n.
  • Variable Initialization:
    • Inside the function, a variable $x is declared and set to the value 51.
  • Conditional Check:
    • The function checks if $n is greater than $x (51).
      • If $n is greater than $x: It returns ( $n - $x ) * 3, which is three times the difference between $n and $x.
      • If $n is not greater than $x: It returns $x - $n, the difference between $x and $n.
  • Function Calls and Output:
    • First Call: echo test(53);
      • Since 53 is greater than 51, it outputs (53 - 51) * 3 = 6.
    • Second Call: echo test(30);
      • Since 30 is less than 51, it outputs 51 - 30 = 21.
    • Third Call: echo test(51);
      • Since 51 is equal to 51, it outputs 51 - 51 = 0

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.



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