Explore
Placement Prep

Edit

Edit

# Finding all the roots of a quadratic equation in C, C++, Java and Python | FACE Prep

Published on 10 Mar 2020

Program to find all the roots of a quadratic equation is discussed here.

The general form of a quadratic equation is (ax^2 + bx + c = 0). The highest degree in a quadratic equation is 2. Hence, a quadratic equation will have two roots.

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

x = [-b +/- sqrt(-b^2 - 4ac)]/2a

The discriminant of the quadratic equation is

k = (b^2 - 4ac).

Depending upon the nature of the discriminant, the roots can be found in different ways.

1. If the discriminant is positive, then there are two distinct real roots.
2. If the discriminant is zero, then the two roots are equal.
3. If the discriminant is negative, then there are two distinct complex roots.

Case 1: If the discriminant is positive,

r1 = (-b +?k)/ 2a and r2 =(b +?k)/ 2a are the two roots.

Case 2: If the discriminant is zero,

r1 = r2 = (-b / 2a)are the two roots.

Case 3: If the discriminant is negative,

r1 = (-b +i ?k)/ 2a and r2 =(b + i?k)/ 2a are the two roots.

For example, consider the following equation

2x^2 8x + 3 = 0.

a = 2, b = -8, c = 3
﻿
Discriminant value, k =b^2 - 4ac
= 8^2 - 4*(-8)*3
﻿ = 40
﻿
The discriminant value is positive. Hence, the roots are real and distinct.

r1 = (-b +?k)/ 2a
= (8 +?40) /2*2
= 2.3875

r2 =(b +?k)/ 2a
=(-8 +?40) /2*2
= -0.3875
﻿
r1 = 2.3875andr2 = -0.3875 are the two roots.


## Algorithm to find all the roots of a quadratic equation

1. Input the value of a, b, c.

2. Calculate k = b*b - 4*a*c

3. If (d < 0)

Display "Roots are Imaginary, calculater1 = (-b +i ?k)/ 2a and r2 =(b + i?k)/ 2a.

else if (d = 0)

Display "Roots are Equal" and calculate r1 = r2 = (-b / 2*a)

else

Display "Roots are real and calculate r1 = -b + ?d / 2*a andr2 = -b - ?d / 2*a

4. Print r1 and r2.

5. End the algorithm.

## Program to find all the roots of a quadratic equation

C
C++
Java
Python 3

Output
Input- Enter coefficients a, b and c: 1 2 3 Output- root1 =-1+1.41421 and root2 =-1+1.41421

Time complexity: O(1)

Recommended Programs