w3resource logo

:

php Programming Exercies

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 my_sqrt($n)
{
  $x = $n;
  $y = 1;
  while($x > $y)
  {
    $x = ($x + $y)/2;
    $y = $n/$x;
  }
  return $x;
}
print_r(my_sqrt(16)."\n");
print_r(my_sqrt(14)."\n");
?>

Sample Output:

4                                                           
3.7416573867739      

Flowchart:

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

PHP Code Editor:

Improve this sample solution and post your code through Disqus