In this tutorial you will learn about the Java Program to Find all Roots of a Quadratic Equation and its application with practical example.
In this tutorial, we will learn to create a Java program that will Find all Roots of a Quadratic Equation using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in java programming.
- Basic input/output in java programming.
- Basic in java programming.
- Inbuilt library functions in java programming.
What is a Quadratic Equation?
In particular, it is a second-degree polynomial equation, since it has the greatest power is two.In algebra said a quadratic polynomial, a polynomial of degree 2.
Java Program to Find All Roots of a Quadratic Equation
In this program, we will Find All Roots of a Quadratic Equation. First of all we declare and initialize the required variables. Next, we would prompt the user to input the values of a,b, and c then with the help of sqrt() function we will calculate the first and second root or equations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
public class QuadRootPro { public static void main(String[] args) { // value a, b, and c double a = 2.3, b = 4, c = 5.6; double root1, root2; // calculate the determinant (b2 - 4ac) double determinant = b * b - 4 * a * c; // check if determinant is greater than 0 if (determinant > 0) { // two real and distinct roots root1 = (-b + Math.sqrt(determinant)) / (2 * a); root2 = (-b - Math.sqrt(determinant)) / (2 * a); System.out.format("root1 = %.2f and root2 = %.2f", root1, root2); } // check if determinant is equal to 0 else if (determinant == 0) { // two real and equal roots // determinant is equal to 0 // so -b + 0 == -b root1 = root2 = -b / (2 * a); System.out.format("root1 = root2 = %.2f;", root1); } // if determinant is less than zero else { // roots are complex number and distinct double real = -b / (2 * a); double imaginary = Math.sqrt(-determinant) / (2 * a); System.out.format("root1 = %.2f+%.2fi", real, imaginary); System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary); } } } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- a,b,c = for holding coordinates
- root1= shows first root.
- root2= shows the second root.
In this program first of we prompted user to input values of a,b and c
after getting the values of a,b and c and with the help of inbuilt function sqrt() and mathematical formula we know to calculate all Roots of a Quadratic Equation.
whose value define in math.h header file we going to find the Second Order Quadratic Equation.
As we know the formula of Quadratic Equation. we will use formula to get first and second root of given coordinates using Java program.