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
- Let N be the number whose square root we need to calculate.
- Initialize start = 0 and end = N.
- Repeat the following steps while (end – start) > 0.00001 (it defines the precision)
- Set mid = (start+end)/2.
- If mid*mid < N, then set start = mid.
- If mid*mid >= N, then set end = mid.
- 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()