w3resource logo


php exercises

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
Output : 4

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

Output :

4                                                           
3.7416573867739      

Flowchart:

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

PHP Code Editor:

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

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number