Cocubes coding | All roots of quadratic equation

In this blog, we will learn how to find all the roots present in the equation.

First of all, you should have basic knowledge of the quadratic equation.

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.

Solving a quadratic equation:

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.

Implementation Using Java:

import java.util.*;

public class Main{
    public static void main(String[] args)
        double a, b, c, dis, r1, r2, rp, ip;
        Scanner sc = new Scanner(;
        a = sc.nextDouble();
        b = sc.nextDouble();
        c = sc.nextDouble();
        dis = b*b - 4*a*c; //discriminant
        if(dis > 0)
            r1 = (-b + Math.sqrt(dis))/(2*a);
            r2 = (-b - Math.sqrt(dis))/(2*a);
            System.out.println("root 1 =" + r1 + "and root 2 = "+r2); 
            rp = -b/(2*a);
            ip = Math.sqrt(-dis)/(2*a);
            System.out.println("root 1 = "+rp+ "+" +ip+"and root 2="+ rp + "+" + ip);
1 2 3
root 1 =-1+1.141421 and root 2 =-1+1.41421

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

#blog #interview #placement #learn #computer #science

        Contact Us

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door