Finding Roots of a quadratic equation

This is the Java Program to Find the Roots of a Quadratic Equation.

The Standard Form of a Quadratic Equation looks like this:

        ax2+bx+c=0
  • ab and c are known values. a can’t be 0.
  • x” is the variable.

We need to find roots for quadratic equation .

Java program for finding the roots of a quadratic equation

Explanation:

A quadratic equation is an equation of the second degree, meaning it contains at least one term that is squared. The standard form is ax² + bx + c = 0 with a, b, and c being constants, or numerical coefficients, and x is an unknown variable. One absolute rule is that the first constant “a” cannot be a zero.

Implementation :

Step 1) Start

Step 2)Take user Input for coefficients namely a ,b,c

Step3) To calculate the roots −

  • Calculate the determinant value (b*b)-(4*a*c).
  • If determinant is greater than 0 roots are [-b +squareroot(determinant)]/2*a and [-b -squareroot(determinant)]/2*a.
  • If determinant is equal to 0 root value is (-b+Math.sqrt(d))/(2*a)

step 4) Print answer 

step 5) End

Java code :

//Java Program to Find the Roots of a Quadratic Equation
 
import java.util.*;
import java.io.*;
 
public class PrepInsta {
    // Function to find and display the roots of quadratic equation
    public static void main(String[] args) {
        Scanner scnew Scanner(System.in);
        double a,b,c;
            System.out.println(“Enter the coefficients of the quadratic equation”);
            a = sc.nextDouble();
            b = sc.nextDouble();
            c = sc.nextDouble();
        
        double determinant = Math.pow(b,2) – 4*a*c;
        if(determinant > 0){
            System.out.println(“Roots are “ + (-b+Math.sqrt(determinant))/(2*a)
                                  + ” and “ + (-b-Math.sqrt(determinant))/(2*a));
        }else if (determinant == 0){
            System.out.println(“Roots are “ + -b/(2*a));
        }
        else{
            System.out.println(“Roots are “ + -b/(2*a) + “+i” + 
                                Math.sqrt(-determinant)/(2*a) + ” and “
                                + -b/(2*a) + “-i” + Math.sqrt(-determinant)/(2*a));
        }
    }
}
Output:

Enter the coefficients of the quadratic equation 1 -5 6 Roots are 3.0 and 2.0