Square root c++ – sqrt() function with custom implementation

By | January 26, 2020

Basics – What is Square Root?

Let’s say there is a number X, when we multiply X with itself, it gives Y. So, X is the square root of Y.
E.g. 2 is the square root of 4
5 is the square root of 25.

Square root in C++ – sqrt() function

C++ provides us an inbuilt library function to calculate the square root of any non-negative number.

If we pass a negative number as a parameter, then it will result in a domain error.

sqrt() function is defined in <cmath> header file. So, we need to include it in our program.

#include <cmath>

Program to get Square Root in C++ using sqrt() function

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	double squareNumber = 25.0, sqrtValue;
	sqrtValue = sqrt(squareNumber);
	cout << "Square root of " << squareNumber << " is " << sqrtValue << endl;
	return 0;
}

Output

c++ square root

Also Read – Solved – Undefined reference to ‘pthread_create’ in Linux with Explanation

Square root function c++ in Code – Without sqrt

#include<stdio.h>

int mySqrt(int num) {

    float temp, sqrt;
    int number;
    number = num;
    sqrt = number / 2;
    temp = 0;

    // It will stop only when temp is the square of our number
    while(sqrt != temp){

        // setting sqrt as temp to save the value for modifications
        temp = sqrt;

        // main logic for square root of any number (Non Negative)
        sqrt = ( number/temp + temp) / 2;
    }

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

int main() {
    int number;

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

    scanf("%d", &amp;number);
    mySqrt(number);
}

Explanation of Above Code

In the above code, we created a function, that takes the entered number as a parameter.

We are maintaining two more variables here, one for storing the temporary value. And the other one for storing the actual square root of the number.

sqrt = ( number/temp + temp) / 2;

This one line code is the core logic behind the calculation.

Final Words

I hope you must have learned how to take the square root in c++ with two methods. If you have a better solution to the problem please comment that below or contact us via E-mail.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.