C++ Program to Find All Roots of a Quadratic Equation


A quadratic equation is in the form ax2 + bx + c. The roots of the quadratic equation are given by the following formula −

Quadratic Equation

There are three cases −

b2 < 4*a*c - The roots are not real i.e. they are complex

b2 = 4*a*c - The roots are real and both roots are the same.

b2 > 4*a*c - The roots are real and both roots are different

The program to find the roots of a quadratic equation is given as follows.

Example

#include<iostream>
#include<cmath>
using namespace std;
int main() {
   int a = 1, b = 2, c = 1;
   float discriminant, realPart, imaginaryPart, x1, x2;
   if (a == 0) {
      cout << "This is not a quadratic equation";
   }else {
      discriminant = b*b - 4*a*c;
      if (discriminant > 0) {
         x1 = (-b + sqrt(discriminant)) / (2*a);
         x2 = (-b - sqrt(discriminant)) / (2*a);
         cout << "Roots are real and different." << endl;
         cout << "Root 1 = " << x1 << endl;
         cout << "Root 2 = " << x2 << endl;
      } else if (discriminant == 0) {
         cout << "Roots are real and same." << endl;
         x1 = (-b + sqrt(discriminant)) / (2*a);
         cout << "Root 1 = Root 2 =" << x1 << endl;
      }else {
         realPart = (float) -b/(2*a);
         imaginaryPart =sqrt(-discriminant)/(2*a);
         cout << "Roots are complex and different." << endl;
         cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" <<end;
         cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" <<end;
      }
   }
   return 0;
}

Output

Roots are real and same.
Root 1 = Root 2 =-1

In the above program, first the discriminant is calculated. If it is greater than 0, then both the roots are real and different.

This is demonstrated by the following code snippet.

if (discriminant > 0) {
   x1 = (-b + sqrt(discriminant)) / (2*a);
   x2 = (-b - sqrt(discriminant)) / (2*a);
   cout << "Roots are real and different." << endl;
   cout << "Root 1 = " << x1 << endl;
   cout << "Root 2 = " << x2 << endl;
}

If the discriminant is equal to 0, then both the roots are real and same. This is demonstrated by the following code snippet.

else if (discriminant == 0) {
   cout << "Roots are real and same." << endl;
   x1 = (-b + sqrt(discriminant)) / (2*a);
   cout << "Root 1 = Root 2 =" << x1 << endl;
}

If the discriminant is less than 0, then both the roots are complex and different. This is demonstrated by the following code snippet.

else {
   realPart = (float) -b/(2*a);
   imaginaryPart =sqrt(-discriminant)/(2*a);
   cout << "Roots are complex and different." << endl;
   cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" << endl;
   cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl;
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 24-Jun-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements