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

Write a C++ program that calculates and displays all roots of a given quadratic equation. The roots may be real or complex depending on the discriminant value.

Input and Output Examples

  1. Input: Coefficients: a = 1, b =−3, c =2 

    Output: Roots are 2 and 1.

  2. Input: Coefficients: a = 1, b = 2, c = 5 

    Output: Roots are -1+i2 and -1-i2.

Algorithm to find the roots of a Quadratic Equation

  1. Prompt the user to input the coefficients a, b, and c.
  2. Calculate the discriminant D=b^2−4ac.
  3. Based on the discriminant:
    • If D>0, compute two distinct real roots.
    • If D=0, compute one real root (repeated).
    • If D<0, compute two complex roots.
  4. Display the roots.

Below is the C++ code to find all roots of a quadratic equation

cpp

#include <iostream>
#include <cmath> // Include the cmath library for sqrt() function
using namespace std;

int main() {
    double a, b, c, discriminant, root1, root2, realPart, imagPart;

    // Step 1: Input coefficients a, b, and c
    cout << "Enter coefficients a, b and c: ";
    cin >> a >> b >> c;

    // Step 2: Calculate the discriminant
    discriminant = b*b - 4*a*c;

    // Step 3: Compute roots based on the discriminant
    if (discriminant > 0) {
        // Two distinct real roots
        root1 = (-b + sqrt(discriminant)) / (2*a);
        root2 = (-b - sqrt(discriminant)) / (2*a);
        cout << "Roots are " << root1 << " and " << root2 << ".";
    } else if (discriminant == 0) {
        // One real root (repeated)
        root1 = root2 = -b / (2*a);
        cout << "Root is " << root1 << ".";
    } else {
        // Two complex roots
        realPart = -b / (2*a);
        imagPart = sqrt(-discriminant) / (2*a);
        cout << "Roots are " << realPart << "+i" << imagPart << " and " << realPart << "-i" << imagPart << ".";
    }

    return 0; 
}

Variations with Different Input Values

This program is equipped to handle all possible scenarios for the roots of a quadratic equation. Here are additional examples with diverse inputs:
 

  1. Input: Coefficients a=1,b=−2,c=1 Output: Root is 1.
  2. Input: Coefficients a=1,b=0,c=1 Output: Roots are 0+i1 and 0-i1.

Programming

5293

889

Related Articles