Javatpoint Logo
Javatpoint Logo

Java Program to Solve Quadratic Equation

In algebra, a quadratic equation is an equation that can be reordered in standard form. The standard form of a quadratic equation is ax2+bx+c=0. It is also known as the second-degree equation. In this section, first will discuss the quadratic equation after that we will create Java programs to solve the quadratic equation by using different approaches.

In the equation ax2+bx+c=0, a, b, and c are unknown values and a cannot be 0. x is an unknown variable. The formula to find the roots of the quadratic equation is known as the quadratic formula.

Java Program to Solve Quadratic Equation

A quadratic equation has two roots and the roots depend on the discriminant. In the above formula, (√b2-4ac) is called discriminant (d). The value of d may be positive, negative, or zero.

If d is positive (d>0), the root will be:

If the value of d is positive, both roots are real and different. It means there are two real solutions.

Java Program to Solve Quadratic Equation

If d is zero (d=0), the root will be:

If the value of d is zero, both roots are real and the same. It means we get one real solution.

Java Program to Solve Quadratic Equation

If d is negative (d<0), the root will be:

If the value of d is negative, both roots are distinct and imaginary or complex. It means that there are two complex solutions.

Java Program to Solve Quadratic Equation

Algorithm to Find the Roots of the Quadratic Equation

Step 1: Start

Step 2: Read a, b, c

Step 3: initialize d<-(b*b)-(4*a*c)

Step 4: initialize r<- b/2*a

Step 5: if d>0 go to Step 6, else go to Step 8

Step 6: r1=r+(sqrt(d)/2*a) and r2=r-(sqrt(d)/2*a)

Step 7: prints roots are real and distinct, first root r1 second root r2

Step 8: if d=0 go to Step 9, else go to Step 10

Step 9: print roots are real and equal, -r

Step 10: d=-d

Step 11: im=sqrt(d)/2*a

Step 12: print roots are imaginary, first root is r+i im, and the second root is r-i im

Step 13: Stop

Let's create a Java program and implement the above steps.

Using if-else

QuadraticEquationExample1.java

Output 1:

Java Program to Solve Quadratic Equation

Output 2:

Java Program to Solve Quadratic Equation

Using Function

QuadraticEquationExample2.java

Output 1:

Java Program to Solve Quadratic Equation

Output 2:

Java Program to Solve Quadratic Equation

Output 3:

Java Program to Solve Quadratic Equation





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA