# C++ Program to find roots of a quadratic equation

## Program to find roots of a quadratic equation

Here we will discuss how to find the roots of a quadratic equation using the C++ programming language.

An equation is said to be a quadratic equation if it’s in the form, ax2+bx+c = 0 (where a!= 0).

To find the roots of any quadratic equation first we need to find the Discriminant(D) and the basis of D we finds the roots and D is given by

D = b2 – 4 * a * c

• If D is greater than 0 then the roots are real and different.
• If D is equal to 0 then the roots are real and equal.
• If D is less than 0 then the roots are complex and different.

### Working

Let’s see how the code works:

• User gives three inputs(three coefficients).
• The inputs are stores in three float type variable say a, b & c.
• The discriminant is found

d = b*b – 4*a*c

• If d is greater than 0, real and different roots are found.

root1 = (-b + sqrt(d)) / (2*a);

root2 = (-b – sqrt(d)) / (2*a);

• If d is less than 0, complex(imaginary) roots are found.

real = -b/(2*a);

imaginary =sqrt(-d)/(2*a);

• If d is equal to 0 then real and equal roots are found.

root1 = (-b + sqrt(d)) / (2*a);

### C++ Code

`//C++ Program//Roots of a equation#include<iostream>#include<math.h>using namespace std;//Main Programint main(){	float d, root1, root2, a, b, c, real, imaginary;	cout << "Enter coefficients a, b and c: ";	//user input	cin>>a>>b>>c;	//finding discriminant	d = (b*b) - (4*a*c);	//for real and different roots	if (d > 0)	{		root1 = (-b + sqrt(d)) / (2*a);		root2 = (-b - sqrt(d)) / (2*a);		cout << "Roots are real and different." << endl;		cout << "root1 = " << root1 << endl;		cout << "root2 = " << root2 << endl;	}	//for imaginary roots	else if (d<0) 	{		real = -b/(2*a);		imaginary =sqrt(-d)/(2*a);		cout << "Roots are complex and different."  << endl;		cout << "root1 = " << real << "+" << imaginary << "i" << endl;		cout << "root2 = " << real << "-" << imaginary << "i" << endl;	}	//for real and equal roots	else 	{		cout << "Roots are real and same." << endl;		root1 = (-b + sqrt(d)) / (2*a);		cout << "root1 = root2 =" << root1 << endl;	}	return 0;}`

#### Output

`Enter coefficients a, b and c: 156Roots are real and different.root1 = -2root2 = -3`