C Math sqrt() Function

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
<math.h>

What You’ll Learn

The sqrt() function computes the square root of a non-negative number—the value that, when multiplied by itself, gives the original. It is one of the most-used functions in geometry, physics, and graphics.

01

√x

Square root.

02

math.h

Link -lm.

03

x ≥ 0

Domain.

04

sqrt(25)=5

Classic.

05

vs pow

Prefer sqrt.

06

NaN

Negative in.

Definition and Usage

The square root of x is the non-negative number y such that y × y = x. In C, sqrt(25.0) returns 5.0 because 5 × 5 = 25.

The domain is x ≥ 0. Passing a negative value returns NaN (Not a Number). Zero is valid: sqrt(0) = 0.

💡
Beginner Tip

Use sqrt(x) instead of pow(x, 0.5) for square roots—clearer and usually faster. For distance between two points, consider hypot(dx, dy) instead of sqrt(dx*dx + dy*dy) to avoid overflow.

📝 Syntax

Standard C declaration:

C
double sqrt(double x);

Related variants

C
float sqrtf(float x);             /* <math.h> */
long double sqrtl(long double x); /* <math.h> */

Parameters

  • x — non-negative value; domain is x ≥ 0.

Return Value

  • Non-negative square root of x as double.
  • sqrt(25.0) returns 5.0.
  • sqrt(0) returns 0.0.
  • sqrt(negative) returns NaN.

Headers and linking

  • #include <math.h>
  • Compile: gcc sqrt.c -std=c11 -o sqrt -lm
  • Check invalid results with isnan() from <math.h>.

⚡ Quick Reference

CallMeaningResult
sqrt(0)√00
sqrt(1)√11
sqrt(25)√255
sqrt(2)√21.414
sqrt(-1)InvalidNaN
Square root
sqrt(x)

x ≥ 0

Cube root
cbrt(x)

Any real x

Distance
hypot(dx,dy)

Safe length

Avoid
pow(x, 0.5)

Use sqrt

Examples Gallery

Compile every example with gcc file.c -std=c11 -o out -lm. Square roots appear everywhere from Pythagorean triangles to normalizing vectors.

📚 Getting Started

Compute the square root of a perfect square.

Example 1 — Square Root of 25

Classic example from the reference: sqrt(25.0).

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

int main(void) {
    double number = 25.0;
    double result = sqrt(number);

    printf("Square root of %.0f is %.0f\n", number, result);

    return 0;
}

How It Works

25 is a perfect square: 5 × 5 = 25, so sqrt(25) is exactly 5.

Example 2 — Square Root of 2

Not every square root is a whole number.

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

int main(void) {
    double x = 2.0;
    double root = sqrt(x);

    printf("sqrt(%.0f) = %.6f\n", x, root);
    printf("Check: %.6f * %.6f = %.6f\n", root, root, root * root);

    return 0;
}

How It Works

√2 ≈ 1.414 is irrational—it cannot be written as a simple fraction. Floating-point gives a close approximation.

📈 Practical Patterns

Geometry, comparison with pow, and error handling.

Example 3 — Pythagorean Distance (3-4-5 Triangle)

Find the hypotenuse: sqrt(a² + b²).

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

int main(void) {
    double a = 3.0;
    double b = 4.0;
    double c = sqrt(a * a + b * b);

    printf("Sides: %.0f and %.0f\n", a, b);
    printf("Hypotenuse: %.0f\n", c);

    return 0;
}

How It Works

3² + 4² = 9 + 16 = 25, and sqrt(25) = 5. For large coordinates, prefer hypot(a, b) to avoid overflow in a*a + b*b.

Example 4 — sqrt() vs pow(x, 0.5)

Both compute square roots—sqrt is the idiomatic choice.

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

int main(void) {
    double x = 49.0;

    printf("x = %.0f\n", x);
    printf("sqrt(x)      = %.1f\n", sqrt(x));
    printf("pow(x, 0.5)  = %.1f\n", pow(x, 0.5));

    return 0;
}

How It Works

Same numeric result, but sqrt reads better and is often optimized as a dedicated instruction.

Example 5 — Handling Negative Input

Validate before calling sqrt, or detect NaN after.

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

int main(void) {
    double values[] = { 16.0, -4.0, 0.0 };
    size_t i;

    for (i = 0; i < 3; i++) {
        double x = values[i];
        if (x < 0.0) {
            printf("sqrt(%.0f): skipped (negative)\n", x);
            continue;
        }
        printf("sqrt(%.0f) = %.1f\n", x, sqrt(x));
    }

    return 0;
}

How It Works

sqrt(-4) would return NaN without a check. Real numbers have no square root in the standard reals—guard your inputs in production code.

🚀 Common Use Cases

  • Geometry — side length from area, Pythagorean theorem.
  • Graphics — vector length, normalizing direction vectors.
  • Physics — speed from kinetic energy, RMS calculations.
  • Statistics — standard deviation uses square roots.
  • Signal processing — magnitude of complex values.

🧠 How sqrt() Works

1

Receive x ≥ 0

Non-negative input (negative → NaN).

Input
2

Compute √x

Library uses hardware sqrt or iterative methods.

Compute
3

Return non-negative root

Principal (positive) square root as double.

Output
=

Square root

sqrt(x) * sqrt(x) ≈ x for valid inputs.

📝 Notes

  • Domain: x ≥ 0. Negative input → NaN.
  • Returns the principal (non-negative) root only.
  • sqrt(0) = 0; perfect squares yield exact integers in output.
  • Prefer sqrt over pow(x, 0.5).
  • For distances, prefer hypot(dx, dy) over manual squaring.
  • Link with -lm on GCC/Clang Unix-like builds.

⚡ Optimization

sqrt() is often implemented in hardware and is fast. Avoid replacing it with Newton’s method unless profiling shows it matters. For comparing distances without the actual length, compare squared distances (dx*dx + dy*dy) to skip sqrt entirely in sorting or collision broad-phase checks.

Conclusion

sqrt() computes the non-negative square root for x ≥ 0. It is essential for geometry, vectors, and statistics. Validate inputs, prefer it over pow, and use hypot for safe distance calculations.

Continue with tan() for trigonometry, or review cbrt() for cube roots.

💡 Best Practices

✅ Do

  • Check x ≥ 0 before calling sqrt
  • Use sqrt instead of pow(x, 0.5)
  • Use hypot for 2D/3D distances when values are large
  • Compare squared distances when you only need ordering
  • Include <math.h> and link -lm

❌ Don’t

  • Pass negative values without handling NaN
  • Expect complex/imaginary results from sqrt in C
  • Use sqrt(dx*dx + dy*dy) for huge coordinates
  • Assume sqrt of non-perfect squares is exact
  • Forget that sqrt returns double, not int

Key Takeaways

Knowledge Unlocked

Five things to remember about sqrt()

Square root in C, explained simply.

5
Core concepts
📚 02

x ≥ 0

Domain.

Rule
📈 03

sqrt(25)=5

Perfect sq.

Example
📄 04

vs pow

Prefer sqrt.

Style
🔄 05

NaN

Negative.

Error

❓ Frequently Asked Questions

sqrt(x) returns the non-negative square root of x. For example, sqrt(25.0) is 5.0 and sqrt(2.0) is about 1.414. If y = sqrt(x), then y * y equals x (for x >= 0).
Include <math.h> and link with -lm on many systems: gcc program.c -o program -lm. The function is declared as double sqrt(double x).
sqrt(negative) returns NaN (Not a Number) and may set errno to EDOM. The domain is x >= 0 only. Always validate input is non-negative, or check the result with isnan().
Prefer sqrt(x) for square roots. It is clearer, typically faster, and expresses intent better than pow(x, 0.5). Use pow only when the exponent is not 0.5.
sqrt(x) computes the square root (power 1/2). cbrt(x) computes the cube root (power 1/3). sqrt(27) is about 5.196; cbrt(27) is 3.0.
sqrtf(x) takes float and returns float. sqrtl(x) takes long double and returns long double. Use the variant matching your variable type.
Did you know?

In game development, collision checks often compare squared distances (dx*dx + dy*dy) instead of calling sqrt, because if d1² < d2² then d1 < d2. That skips an expensive square root when you only need to know which point is closer.

Explore C Math Functions

Continue with tan() or browse the full math function reference.

Math Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful