# C# program to find the root of a quadratic equation

Here, we are going to learn how to find the root of a quadratic equation in C#?
Submitted by Nidhi, on October 09, 2020

Here we will find the root of the Quadratic equation.

Program:

The source code to find the root of a Quadratic equation is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

```//C# program to find the root of a Quadratic Equation.

using System;

{
public static void ComputeRoot(double a, double b, double c)
{
double root1   =   0;
double root2   =   0;
double eq      =   0;

eq = b * b - 4 * a * c;

if (a == 0)
{
}
else if (eq > 0)
{
Console.WriteLine("Roots are Real and Distinct");
root1 = (-b + Math.Sqrt(eq)) / (2 * a);
root2 = (-b - Math.Sqrt(eq)) / (2 * a);

Console.WriteLine("Root1: {0:#.##}", root1);
Console.WriteLine("Root2: {0:#.##}", root2);
}
else if (eq == 0)
{
Console.WriteLine("Roots are Real and Equal");
root1 = root2 = (-b) / (2 * a);

Console.WriteLine("Root1: {0:#.##}", root1);
Console.WriteLine("Root2: {0:#.##}", root2);
}
else
{
Console.WriteLine("Roots are Imaginary");
root1 = (-b) / (2 * a);
root2 = Math.Sqrt(-eq) / (2 * a);

Console.WriteLine("Root1: {0:#.##} + i{1:#.##}" ,root1, root2);
Console.WriteLine("Root2: {0:#.##} - i{1:#.##}" ,root1, root2);
}
}

public static void Main()
{
double a=0;
double b=0;
double c=0;

Console.WriteLine("Quadratic equation a*x*x + b*x + c = 0");

Console.Write("Enter the value of A: ");

Console.Write("Enter the value of B: ");

Console.Write("Enter the value of C: ");

ComputeRoot(a, b, c);
}
}
```

Output:

```Quadratic equation a*x*x + b*x + c = 0
Enter the value of A: 10
Enter the value of B: 5
Enter the value of C: 2
Roots are Imaginary
Root1: -.25 + i.37
Root2: -.25 - i.37
Press any key to continue . . .
```

Explanation:

Here, we created a class QuadRoot that contains two methods ComputeRoot() and Main() method.

The ComputeRoot() method is used to find the root of the quadratic equation based on the value of a, b, and c.

Here we check different conditions for the quadratic equation and then find the root accordingly.

In the Main() method, we created three variables a, b, and c that is initialized with 0. Then the passed the variables a, b, and c into ComputeRoot() method to calculate the roots for the quadratic equation.