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

C Programming Language Loop control in C Language (Article) Loop control in C Language (Program)

1916

Program:


/* 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

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.