Home / Programs / Write a program to compute the square root of a given number (without using sqrt() function of the math library).
Programming Example

Write a program to compute the square root of a given number (without using sqrt() function of the math library).

👁 2,037 Views
💻 Practical Program
📘 Step by Step Learning
Write a program to compute the square root of a given number (without using sqrt() function of the math library).

Program Code


/* C progarm to compute the square root of a given number */

#include <stdio.h>
#include <math.h>

int main(void)
{
	float m, f,s;
	printf("\n Enter the number:  ");
	scanf("%f",&m);
	/* Checking for negative input */
	if(m<0)
	{
		printf("\n Negative Input For Computing Square Root Is Not Allowed");
		return 0;
	}
	s=m/2; /* Set the initial guess */
	do
	{
		f=s;
		s=(f+m/f)/2;  /* Compute the next estimate for the square root */ 
		
	}while(fabs(f-s)>=0.000001);
	
	printf("\n Square root of %g is %g\n",m,s);

    getch();
	return 0;
}

Output


 Enter the number:  36

 Square root of 36 is 6

Explanation

None

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.