Home C Programming Language / 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,038 Views
💻 Practical Program
📘 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;
}

                        

🖥 Program Output


 Enter the number:  36

 Square root of 36 is 6

                            

📘 Explanation

None
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.