How to Find the Square Root of a Number in C#?

To calculate the square root of a number in C#, you use the Math.Sqrt() method which returns a double representing the principal square root of the input. If the input is negative, Math.Sqrt() returns NaN.

Whether you’re processing statistical data, building games with Unity, or performing numeric computations in business or AI applications, calculating a square root reliably in C# is a common task. While the built-in Math.Sqrt() method is simple to use, understanding its behavior with different inputs — including negative numbers and precision limits — helps you write accurate, efficient, and error-free programs.

Key Takeaways of the Square root of a number in C#

ConceptDescription
Use Math.Sqrt(double value) for most cases.The simplest and most accurate method to compute square roots.
If value < 0, result is NaN.Avoids invalid mathematical operations automatically.
Custom square root algorithms may be used when avoiding Math.Sqrt() or for integer results.Useful for optimization or integer-specific programs.
Watch for performance if you’re doing millions of operations.Heavy use in loops can affect speed in large computations.
Always choose double for input, and cast/convert appropriately if using other numeric types.Ensures precision and prevents type mismatch errors.
Square root of a number in C#

What is the Math.Sqrt() Method in C#?

The Math.Sqrt() method in C# is a built-in mathematical function used to calculate the square root of a given number. It’s part of the System namespace and works with the double data type.

Syntax:

public static double Sqrt(double d)

Microsoft Learn +1

This method returns the principal (non-negative) square root of the specified number.

Syntax and Basic Usage

Here’s a simple example to demonstrate how Math.Sqrt() works in C#:

double value = 25;
double result = Math.Sqrt(value);
Console.WriteLine(result); // output: 5

If the input is zero, the output will also be zero. However, if the input is negative, the method returns NaN (Not a Number) since square roots of negative numbers are not real.

What Happens with Invalid or Edge-Case Input?

When handling edge cases, the Math.Sqrt() method behaves predictably:

  • Negative input → returns NaN
  • Zero → returns 0
  • Positive Infinity → returns Positive Infinity

This predictable behavior ensures your program remains stable even with extreme or invalid inputs.

Why and When You Might Use a Custom Square-Root Algorithm

Although Math.Sqrt() is accurate and efficient for most applications, some scenarios require custom logic — such as high-volume calculations, integer-only results, or avoiding dependencies on built-in methods.

Performance Concerns

In performance-critical systems, like data simulations or large-scale numerical analysis, repeatedly calling Math.Sqrt() in loops can impact execution time. In such cases, developers may use approximate or optimized algorithms for specific hardware or data types.

Integer Result Only (Floor of Sqrt) Without Using Built-in

If you want to find only the integer part of a square root (floor value) without using the built-in Math.Sqrt() method, you can create your own logic using a simple loop-based approach. This is especially useful when working with integer-only calculations or in restricted environments where you can’t rely on library functions.

Here’s a clean example written from scratch:

int number = 27;
int result = 0;

// Increment result until its square exceeds the number
while ((result + 1) * (result + 1) <= number)
{
    result++;
}

Console.WriteLine($"The integer square root of {number} is {result}");

Explanation:

  • We start with result = 0.
  • The loop continues as long as (result + 1)² is less than or equal to the given number.
  • Once the condition fails, result holds the largest integer whose square does not exceed the original number.

Output:

The integer square root of 27 is 5

This simple and efficient logic avoids floating-point calculations and gives you the floor value of the square root using only integer operations.

Algorithmic Approach (Newton’s Method / Binary Search)

When you need more control over precision and performance, custom algorithms like Newton’s Method or Binary Search can be used to calculate the square root manually. These methods are popular in competitive programming, embedded systems, and low-level mathematical computation where built-in functions may not be ideal.

Example – Newton’s Method (Pure Implementation)

The Newton-Raphson method iteratively improves an initial guess until it gets close enough to the actual square root.

double SquareRoot(double number)
{
    if (number < 0)
        throw new ArgumentException("Cannot compute square root of a negative number.");

    double guess = number / 2;
    double tolerance = 0.00001;

    while (Math.Abs(guess * guess - number) > tolerance)
    {
        guess = 0.5 * (guess + number / guess);
    }

    return guess;
}

Explanation:

  • Start with an initial guess — typically half of the input number.
  • Repeatedly refine the guess using the formula:
    [
    \text{newGuess} = \frac{1}{2} \times (\text{guess} + \frac{\text{number}}{\text{guess}})
    ]
  • Stop when the difference between guess² and the input number becomes smaller than a defined tolerance (e.g., 0.00001).

Example Output:

Square root of 49 is approximately 7.0000000929

This approach is fast, accurate, and doesn’t rely on Math.Sqrt() — making it ideal for environments where you need manual precision control.

Alternative – Binary Search Method

If you prefer an integer-based solution, the binary search method can also be used to find the square root, especially when dealing with large integer inputs.

int IntegerSquareRoot(int number)
{
    if (number < 0)
        throw new ArgumentException("Negative numbers are not supported.");

    int start = 0, end = number, answer = 0;

    while (start <= end)
    {
        int mid = (start + end) / 2;

        if (mid * mid == number)
            return mid;

        if (mid * mid < number)
        {
            start = mid + 1;
            answer = mid;
        }
        else
        {
            end = mid - 1;
        }
    }

    return answer;
}

Explanation:

  • The algorithm keeps narrowing down the range [start, end] until it finds the integer closest to the square root.
  • This approach works efficiently for large integers and avoids floating-point operations.

Example Output:

Integer square root of 50 is 7

Both methods—Newton’s Method and Binary Search—are reliable ways to compute the square root when precision, performance, or environment limitations matter most.

Example Code Snippets

Here’s a complete C# console program to calculate the square root of a number safely:

using System;

class Program {
  static void Main() {
    Console.Write("Enter a number: ");
    if(double.TryParse(Console.ReadLine(), out double number)) {
      if(number >= 0) {
        double sqrt = Math.Sqrt(number);
        Console.WriteLine($"Square root of {number} is {sqrt}");
      } else {
        Console.WriteLine("Cannot compute square root of a negative number.");
      }
    } else {
      Console.WriteLine("Invalid input.");
    }
  }
}

This program checks for invalid input and handles negative numbers gracefully by displaying an appropriate message.

Integer-only Variant (Floor Value)

Here’s a custom algorithm to find only the integer part of the square root without using Math.Sqrt():

int number = 40;
int result = 0;

while (result * result <= number)
{
    result++;
}
result--;

Console.WriteLine($"Integer part of square root of {number} is {result}");

This method is efficient for small integer values and educational purposes where understanding logic is more important than speed.

Pros & Cons of the Square root of a number in C#

ApproachProsCons
Math.Sqrt() built-inSimple, reliable, well-testedMight be slower in extreme loops
Custom algorithm (Newton)Can optimize for special casesMore complex, potential for bugs
Integer-only floor methodUseful when you only need intLoss of precision, manual logic

Real-Life Applications of Calculating the Square root of a number in C#


  1. Finance Calculations at Fintech Companies
    In the world of fintech, companies often need to perform complex mathematical calculations to evaluate financial models, which can include calculating square roots for interest rates or loan payments.
    using System;
    class Program
    {
    static void Main()
    {
    double input = 16.0; // Example loan payment value
    double result = Math.Sqrt(input);
    Console.WriteLine("Square root: " + result); // Output: 4
    }
    }
    The output here illustrates how they utilize the square root for determining projections in financial models.


  2. Game Development in Tech Giants

    Gaming companies, like Unity Technologies, use C# for developing games where 3D graphics computations are common. Calculating distances using square roots is a key task.
    using System;
    class Program
    {
    static void Main()
    {
    double x1 = 3, y1 = 4, x2 = 0, y2 = 0; // Coordinates
    double distance = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
    Console.WriteLine("Distance: " + distance); // Output: 5
    }
    }
    This output helps measure distances between game objects, enhancing gameplay realism.

  3. Engineering Calculations at Aerospace Firms
    Firms such as Boeing use C# for simulations involving physical properties where square roots are vital in calculating things like stress analysis and forces.
    using System;
    class Program
    {
    static void Main()
    {
    double stress = 64.0; // Stress measurement
    double principalStress = Math.Sqrt(stress);
    Console.WriteLine("Principal Stress: " + principalStress); // Output: 8
    }
    }
    This output provides insights for engineers to ensure safety and efficiency in designs.

Square root of a number in C# Queries

 

  1. What’s the easiest way to find a square root in C#?
    The Math.Sqrt() method is your best friend here; it makes finding a square root a piece of cake. Simply use it as shown below:
    double result = Math.Sqrt(25); // Outputs 5.0
  2. How can I handle errors when getting a square root of a negative number?
    Using Math.Sqrt() with a negative number will return NaN (Not a Number). So, checking if your number is negative is a good practice:
    if (number < 0)
    {
        Console.WriteLine("Can't find the square root of a negative number");
    }
  3. Is there a way to calculate a square root without using Math.Sqrt()?
    You can implement your own algorithm, like the Babylonian method, for educational purposes. But for efficiency, stick to Math.Sqrt() in real-life applications.

  4. Can I find a square root of a non-integer number?
    Absolutely! Math.Sqrt() works just fine with non-integers:
    double result = Math.Sqrt(20.25); // Outputs 4.5
  5. What’s the namespace for Math.Sqrt() in C#?
    Math is found in the System namespace, which is included in most C# applications by default. No need to worry about importing something extra!

  6. How can I format the output of Math.Sqrt() to two decimal places?
    Use string formatting or Math.Round():
    Console.WriteLine("{0:F2}", result);
  7. Can I use Math.Sqrt() for complex numbers?
    Math.Sqrt() doesn’t handle complex numbers directly. For complex numbers, look into System.Numerics.Complex.

  8. How can I use Math.Sqrt() in a loop for multiple numbers?
    Simply run Math.Sqrt() inside a loop, processing each number iteratively.
    foreach (int number in numbers)
    {
        Console.WriteLine(Math.Sqrt(number));
    }

 

Our AI-powered csharp online compiler lets users instantly write, run, and test code, making coding seamless and efficient. With AI guidance, it’s like having your own coding assistant. This innovative tool helps coders of all levels improve and succeed faster, ensuring a smooth coding journey. Happy coding!

Conclusion

The ‘C# Program to Find Square Root of a Number’ enhances your understanding of mathematical functions and C# programming. By mastering this skill, you’ll gain confidence and precision in coding tasks. Feel inspired to try it yourself and explore more about languages at Newtum.

Edited and Compiled by

This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.

About The Author