C# Program to Find Square Root of a Number
Math.Sqrt(number). For example, double result = Math.Sqrt(16); will give you 4.Examples
How to Think About It
Math.Sqrt function in C# which does this calculation for us easily.Algorithm
Code
using System; class Program { static void Main() { Console.Write("Enter a number: "); double number = Convert.ToDouble(Console.ReadLine()); double squareRoot = Math.Sqrt(number); Console.WriteLine($"Square root of {number} is {squareRoot}"); } }
Dry Run
Let's trace the input 16 through the code
Input number
User enters 16, so number = 16
Calculate square root
squareRoot = Math.Sqrt(16) which equals 4
Output result
Prints 'Square root of 16 is 4'
| Step | Variable | Value |
|---|---|---|
| 1 | number | 16 |
| 2 | squareRoot | 4 |
| 3 | output | Square root of 16 is 4 |
Why This Works
Step 1: Reading input
We read the number from the user using Console.ReadLine() and convert it to a double for decimal support.
Step 2: Calculating square root
We use Math.Sqrt() which is a built-in C# method that returns the square root of the given number.
Step 3: Displaying result
We print the result using Console.WriteLine() with string interpolation to show the original number and its square root.
Alternative Approaches
using System; class Program { static void Main() { Console.Write("Enter a number: "); double number = Convert.ToDouble(Console.ReadLine()); double squareRoot = Math.Pow(number, 0.5); Console.WriteLine($"Square root of {number} is {squareRoot}"); } }
using System; class Program { static double SqrtNewton(double n) { double x = n; double y = 1; double e = 0.00001; // precision while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } static void Main() { Console.Write("Enter a number: "); double number = Convert.ToDouble(Console.ReadLine()); double squareRoot = SqrtNewton(number); Console.WriteLine($"Square root of {number} is {squareRoot}"); } }
Complexity: O(1) time, O(1) space
Time Complexity
Using Math.Sqrt is a constant time operation because it uses optimized CPU instructions or library calls.
Space Complexity
The program uses a fixed amount of memory for variables, so space complexity is constant.
Which Approach is Fastest?
Math.Sqrt is fastest and most reliable; manual methods like Newton's are slower and mainly educational.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Math.Sqrt | O(1) | O(1) | Fast, simple, built-in |
| Math.Pow with 0.5 | O(1) | O(1) | Alternative, less direct |
| Newton's method | O(k) where k is iterations | O(1) | Learning approximation, no built-in |
Math.Sqrt for a simple and fast way to find square roots in C#.