Square Root in C
×


Square Root in C

26

 Calculating square roots in C programming is essential for various mathematical and scientific computations.

 The square root of a number in C can be obtained using the sqrt() function from the math.h library.

 This function takes a single argument and returns the square root of that number.

 Alternatively, the square root can be calculated without using sqrt() by implementing a custom algorithm.

 One such algorithm divides the number by 2 and iteratively adjusts the approximation until it converges to the square root.

  Using Standard Library Function: Include the header file and call the sqrt() function, providing the number whose square root needs computation.

Using Newton's Method: Implement the Newton-Raphson method iteratively to approximate the square root of the given number.

// Program to calculate square roots in C
#include<stdio.h>

int main() {
    int num;
    float sqrt, temp;
    
    printf("Enter a number to get the square root: ");
    scanf("%d", &num);
    
    sqrt = num / 2;
    temp = 0;
    
    while (sqrt != temp) {
        temp = sqrt;
        sqrt = (num / temp + temp) / 2;
    }
    
    printf("The square root of %d is %.2f\n", num, sqrt);
    
    return 0;
}

Output:

Enter a number to get the square root: 9
The square root of 9 is 3.00

Using Standard Library Function:

//program Using Standard Library Function
#include<stdio.h> 
#include 

int main() {
    double num = 25.0;
    double result = sqrt(num);
    printf("Square root of %f is %f\n", num, result);
    return 0;
}
	

output:

Square root of 25.000000 is 5.000000

Program Using Newton's Method:

// Program Using Newton's Method
#include<stdio.h> 
#include<math.h>
double squareRoot(double num) {
    double x = num;
    double root = 0.0;
    while (1) {
        root = 0.5 * (x + (num / x));
        if (fabs(root - x) < 0.0001) break;
        x = root;
    }
    return root;
}

int main() {
    double num = 25.0;
    double result = squareRoot(num);
    printf("Square root of %f is %f\n", num, result);
    return 0;
}

Output:

Square root of 25.000000 is 5.000000


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments