Learn how to retrieve the square root of a number without using the math header in C

How to get the square root of a number without using the sqrt function in C

Every C programmer knows about the math.h header file of the C programming language. This header defines various mathematical functions and one macro. All the functions available in this library take double as an argument and return a double as result. 

One of the known features of this library is the sqrt function, the pretty useful function double sqrt(double number) that returns the square root of number:

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

int main () {
   /// 2.000000
   printf("Square root of %lf is %lf\n", 4.0, sqrt(4.0) );
   /// 2.236068
   printf("Square root of %lf is %lf\n", 5.0, sqrt(5.0) );
   
   return(0);
}

Pretty easy right? However, teachers at universities don't like to let the things easy for students, that's why in programming classes you may need to find a way to find the square root of a number without using this library in C !

What Horseman Whaaat

As homeworks or tasks aren't optional, we'll show you how you can easily achieve this goal without using the sqrt function in C.

Implementation

To get started, we'll expose you the solution directly and we'll explain at the end of the article:

#include<stdio.h>

void main()
{
    int number;

    float temp, sqrt;

    printf("Provide the number: \n");

    scanf("%d", &number);

    // store the half of the given number e.g from 256 => 128
    sqrt = number / 2;
    temp = 0;

    // Iterate until sqrt is different of temp, that is updated on the loop
    while(sqrt != temp){
        // initially 0, is updated with the initial value of 128
        // (on second iteration = 65)
        // and so on
        temp = sqrt;

        // Then, replace values (256 / 128 + 128 ) / 2 = 65
        // (on second iteration 34.46923076923077)
        // and so on
        sqrt = ( number/temp + temp) / 2;
    }

    printf("The square root of '%d' is '%f'", number, sqrt);
}

The code works like this: initially, the program will prompt the user for the number from which we want to find the square root. We will store the half of the number in a variable dividing it by 2, namely sqrt. Then, we will declare a temp variable that will store a copy of the previous value of sqrt namely temp. Finally, we will loop until the sqrt variable is different of temp, inside we will update the value of temp with the previous sqrt value and so on. The sqrt value is update by the described operation in the code and that's it. Once the loop ends, you will be able to print the square root of the number.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors