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

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

x = −b ± √ b² − 4ac 2a

The value b2 − 4ac is called the discriminant. It determines the nature of the roots. There are three cases −

  • b2 > 4ac − The roots are real and different.
  • b2 = 4ac − The roots are real and both roots are the same.
  • b2 < 4ac − The roots are not real (they are complex).

Example

The following program calculates the discriminant and then finds the roots based on which case applies ?

#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" << endl;
         cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl;
      }
   }
   return 0;
}

With a=1, b=2, c=1, the discriminant is 2*2 - 4*1*1 = 0, so both roots are equal. The output is ?

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

How the Program Works

First, the discriminant b*b - 4*a*c is calculated. Then the program checks which case applies −

If the discriminant is greater than 0, both roots are real and different. The two roots are computed using the quadratic formula with + and - for the square root term.

If the discriminant is equal to 0, both roots are real and identical. Only one root value needs to be calculated since both are the same.

If the discriminant is less than 0, the roots are complex. The real part is -b/(2a) and the imaginary part is sqrt(-discriminant)/(2a), giving roots of the form realPart ± imaginaryPart*i.

Conclusion

The discriminant b² - 4ac determines whether a quadratic equation has real equal roots, real distinct roots, or complex roots. The sqrt() function from <cmath> handles the square root computation in all three cases.

Updated on: 2026-03-12T23:18:27+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements