C# Program - Square Root of a Number


Advertisements

If a number is multiplied by itself ($$n*n$$), the final number will be the square of that number and finding the square root of a number is inverse operation of squaring the number. If x is the square root of y, it can be expressed as below:

$$x = \sqrt{y}$$

Alternatively, it can also be expressed as:

$$x^2 = y$$

Example: Using Sqrt() method of C# Math Class

The Sqrt() method of C# Math class can be used to return square root of a number.

using System;

namespace MyApplication { 
  class MyProgram {
    static void Main(string[] args) {
	  double x = 16;
	  double y = 25;

	  //Sqrt() takes double datatype as argument
	  double x1 = Math.Sqrt(x);
	  double y1 = Math.Sqrt(y);
	  Console.WriteLine("Square root of " + x + " is " + x1);
	  Console.WriteLine("Square root of " + y + " is " + y1);
    }
  }
}

Output

Square root of 16.0 is 4.0
Square root of 25.0 is 5.0

Example: Using Pow() method of C# Math Class

The Pow() method of C# Math class can also be used to calculate square root of a number.

using System;

namespace MyApplication { 
  class MyProgram {
    static void Main(string[] args) {
	  double x = 16;
	  double y = 25;

	  //Pow() takes double datatype as argument
	  double x1 = Math.Pow(x, 0.5);
	  double y1 = Math.Pow(y, 0.5);
	  Console.WriteLine("Square root of " + x + " is " + x1);
	  Console.WriteLine("Square root of " + y + " is " + y1);
    }
  }
}

Output

Square root of 16.0 is 4.0
Square root of 25.0 is 5.0

Advertisements