In this blog post, I will teach you to how to write a C program to calculate the square root of a given number. By the end of this tutorial, you will be able to efficiently compute the square root using both a built-in library function and an own created function.
Before we dive into the coding part, let’s first understand what the square root of a number is.
The square root of a number n is a value x such that x^2 = n. For example, the square root of 25 is 5 because 5 * 5 = 25.
Example,
Input: number = 9 Output: 3 Input: number = 25 Output: 5
Using inbuilt sqrt() function:
In C, we can use sqrt() function from the math library function to compute the square root of a number. This function computes the nonnegative square root of a given number (sqrt parameters). It takes one argument in the form of double and returns the value of type double. You should remember that if the argument is less than zero, a domain error occurs.
Steps involved in C Program to find square root of any number:
The following steps involved in the below C program.
- Input: We will take input from the user. It is a number whose square root needs to be calculated.
- Validation: The program checks whether the input is negative or positive. If the input is negative, it will display an error message. It is important because sqrt() works only on positive number.
- Calculation: If the number is non-negative, the program will calculate the square root using the
sqrt()function. - Output: The square root of the number will be displayed.
#include <stdio.h>
#include <math.h> // Include math library for sqrt() function
int main()
{
double number;
// Ask the user for input
printf("Enter a number to find its square root: ");
scanf("%lf", &number);
// Check if the number is non-negative
if (number < 0)
{
printf("Error! Square root of a negative number is not a real number.\n");
}
else
{
// Calculate the square root using sqrt() function
const double result = sqrt(number);
printf("The square root of %.2f is %.2f\n", number, result);
}
return 0;
}
Output:
Case 1: Input is a positive number
Enter a number to find its square root: 9 The square root of 9.00 is 3.00
Case 2: Input is a negative number
Enter a number to find its square root: -7 Error! Square root of a negative number is not a real number.
Using Binary Search:
You can also compute the square root of a number using the binary search. This approach works particularly well for finding square roots of numbers within a certain range, and it avoids the iterative process of methods like the Babylonian method.
Let’s see the idea behind the binary search approach is:
- Square root of a given number
nlies between0andn. - So, we can apply binary search within this range to narrow down the potential square root by checking the middle point in each iteration.
- If the square of the middle point is greater than
n, we adjust the search to the lower half of the range. Otherwise, we adjust the search to the upper half. - We continue adjusting the search range until we find a value that, when squared, is sufficiently close to
n.
C Program to Find Square Root Using Binary Search:
#include <stdio.h>
/**
* @brief Function to calculate the square root using binary search.
*
* This function calculates the square root of a number using binary search.
* The binary search method finds the root by comparing the square of the midpoint
* with the original number and adjusting the search range based on the comparison.
*
* @param n The number for which we need to calculate the square root.
* @return The square root of the number.
*/
double sqrtUsingBinarySearch(double n)
{
if (n < 0)
{
printf("Error! Square root of a negative number is not a real number.\n");
return -1;
}
// Special case for 0 and 1, where the square root is the number itself
if (n == 0 || n == 1)
{
return n;
}
// Define the range for binary search
double low = 0, high = n;
double mid, result;
// Define the precision for the result
double epsilon = 0.000001;
// Perform binary search
while ((high - low) > epsilon)
{
mid = (low + high) / 2; // Find the middle point
result = mid * mid; // Square the midpoint
if (result > n)
{
high = mid; // Adjust the upper bound
}
else
{
low = mid; // Adjust the lower bound
}
}
// Return the square root as the average of the low and high bounds
return (low + high) / 2;
}
int main()
{
double number, result;
// Ask user to input a number
printf("Enter a number to find its square root: ");
scanf("%lf", &number);
// compute the square root without using library function
result = sqrtUsingBinarySearch(number);
if (result != -1)
{
printf("The square root of %.2f is approximately %.6f\n", number, result);
}
return 0;
}
Explanation of the above C Code:
-
-
- Mentioned C program uses binary search to find the square root of a given number
n. - The
lowbound is initially set to0and thehighbound is set ton. - We calculate the midpoint (
mid) and check if the square ofmidis close tonwithin the defined precision (epsilon). - If
mid^2is greater thann, we reduce the search range by adjusting thehighbound. Otherwise, we adjust thelowbound. - The process continues until the difference between
highandlowis smaller than the precision threshold. - The program uses an epsilon value of 0.000001 to control the precision of the result. The loop runs until the difference between low and high is smaller than this threshold.
- Mentioned C program uses binary search to find the square root of a given number
-