C Program to find Square Root of a Number

How to write a C Program to find the Square root of a Number using sqrt and without using the sqrt function with an example?

This program allows the user to enter any integer and then find the square root of that number using the math function sqrt(). Please refer to the built-in C sqrt and the C pow function.

#include<stdio.h>
#include<math.h>
 
int main()
{
  	double number, result;
 
 	printf(" \n Please Enter any Number to find : ");
  	scanf("%lf", &number);
  
  	result = sqrt(number);
  
  	printf("\n Square Root a given number %.2lf  =  %.2lf", number, result);
 
  	return 0;
}
C Program to find Square root of a Number

C Program to find the Square root of a Number without using sqrt

This program uses the math function pow to find the square root of a number. As we all know √number = number½. For more topics, refer to the C programs article.

#include<stdio.h>
#include<math.h>
 
int main()
{
	double num, result;
 
  	printf(" \n Please Enter any value : ");
  	scanf("%lf", &num);
  
  	result = pow(num, 0.5);
  
  	printf("\n Result of %.2lf  =  %.3lf", num, result);
 
  	return 0;
}
 Please Enter any value : 3

 Result of 3.00  =  1.73

Square root using log2() function

In the program below, we use the built-in mathematical functions log2() and pow() to calculate the square root of a given number. Refer to the C log2 function.

The math formula = pow(2, 0.5 * log2(n))

#include <stdio.h>
#include <math.h>
double findSqroot(double n)
{
return pow(2, 0.5 * log2(n));
}

int main()
{
int number = 64;
printf("Square Root = %.4f", findSqroot(number));
}
Square Root = 8.0000

Calculate square root using Binary Search

The following program uses the binary search approach to calculate the square root of a number. We initialize the starting value to 0 and the ending value to the given number. Next, we calculate the mid value and compare it with the given number to continue searching for the square root.

#include <stdio.h>
#include <math.h>
double findSqroot(double n)
{
int start = 0, mid, end = n;
float sq;
while (start <= end)
{
mid = (start + end) / 2;
if (mid * mid == n)
{
sq = mid;
break;
}
if (mid * mid < n)
{
sq = start;
start = mid + 1;
}
else
{
end = mid - 1;
}
}
float inc = 0.1;
for (int i = 0; i < 5; i++)
{
while (sq * sq <= n)
{
sq += inc;
}
sq = sq - inc;
inc /= 10;
}
return sq;
}

int main()
{
int number = 7;
printf("Square Root = %.4f", findSqroot(number));
}
Square Root = 2.6457

Also Read