C Program to find the square root of a number

In this article, we will study different ways we can find the square root of a number in C/C++.

Program of Square root using the standard library

The simplest way to find square root of a number is to use the standard library function sqrt().

double sqrt(double arg);

It accepts a single argument of type double and returns the square root of that number. The sqrt() is defined in math.h library.

Example,

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

int main() {
	
	int n;
	double v;
	
	printf("Enter a Number: ");
	scanf("%d",&n);
	
	v = sqrt(n);
	
	printf("Square Root of %d is %f",n,v);
	
}

Output

Enter a Number: 13
Square Root of 13 is 3.605551

Program of Square root using Binary Search Algorithm

We can use binary search to find approximate value of square root of a number.

Steps

  1. Let N be the number whose square root we need to calculate.
  2. Initialize start = 0 and end = N.
  3. Repeat the following steps while (end – start) > 0.00001 (it defines the precision)
    1. Set mid = (start+end)/2.
    2. If mid*mid < N, then set start = mid.
    3. If mid*mid >= N, then set end = mid.
  4. The final answer is stored in mid.
#include<stdio.h>
#include<math.h>

int main() {
	
	int n;
	double start,end,mid;
	
	printf("Enter a Number: ");
	scanf("%d",&n);
	
	start = 0, end = n;
	
	while((end - start)>=0.000001){
		
		mid = (start + end)/2;
		
		if(mid*mid < n)
			start = mid;
		if(mid*mid >= n)
			end = mid;
		
	}
	
	printf("Square Root of %d is %f",n,mid);
	
}

Output

Enter a Number: 13
Square Root of 13 is 3.605551

Read
Check if a number is Prime
Left-Shift Array by One
Reverse a String without strrev()

Leave a Comment

Your email address will not be published.