w3resource

PHP Challenges: Compute and return the square root of a given number

PHP Challenges - 1: Exercise-8 with Solution

Write a PHP program to compute and return the square root of a given number.

Input : 16

Explanation :

PHP: Compute and return the square root of a given number

Sample Solution :

PHP Code :

<?php
// Function to calculate the square root of a number using the Newton's method
function my_sqrt($n)
{
    // Initialize variables $x and $y
    $x = $n;
    $y = 1;

    // Loop until $x is greater than $y
    while($x > $y)
    {
        // Update $x and $y according to Newton's method
        $x = ($x + $y) / 2;
        $y = $n / $x;
    }

    // Return the calculated square root
    return $x;
}

// Test the my_sqrt function with different inputs and print the results
print_r(my_sqrt(16)."\n");
print_r(my_sqrt(14)."\n");
?>

Explanation:

Here is a brief explanation of the above PHP code:

  • The code defines a function named "my_sqrt()" which calculates the square root of a number using Newton's method. It takes a single parameter '$n', which is the number for which the square root is to be calculated.
  • Inside the function:
    • It initializes two variables '$x' and '$y' with initial values of '$n' and 1 respectively.
    • It enters a "while" loop that continues until "$x" is greater than "$y".
    • Within each iteration of the loop, it updates the values of "$x" and "$y" according to Newton's method for finding square roots.
    • After the loop, it returns the calculated square root "$x".
  • Function Call & Testing:
    • The function "my_sqrt()" is called twice with different input values (16 and 14).
    • The results of the function calls are printed using print_r(), which displays the calculated square root for each input value.

Sample Output:

4                                                           
3.7416573867739      

Flowchart:

PHP Flowchart: Compute and return the square root of a given number

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to a given number.
Next: Write a PHP program to find a single number in an array that doesn't occur twice.

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/challenges/1/php-challenges-1-exercise-8.php