## Algorithm

Input: Coefficients a, b, and c of the quadratic equation ax^2 + bx + c = 0

1. Calculate the discriminant (D) using the formula: D = b^2 - 4ac

2. If D > 0:
a. Calculate two real and distinct roots:
root1 = (-b + sqrt(D)) / (2a)
root2 = (-b - sqrt(D)) / (2a)
b. Display "Two real and distinct roots:"
c. Display "Root 1:", root1
d. Display "Root 2:", root2

3. Else if D = 0:
a. Calculate a single real root:
root = -b / (2a)
b. Display "Two real and equal roots:"
c. Display "Root:", root

4. Else (D < 0):
a. Calculate two complex roots:
realPart = -b / (2a)
imaginaryPart = sqrt(|D|) / (2a)
root1 = realPart + imaginaryPart * i
root2 = realPart - imaginaryPart * i
b. Display "Complex roots:"
c. Display "Root 1:", root1
d. Display "Root 2:", root2

## Code Examples

### #1 Code Example- Java Program to Find Roots of a Quadratic Equation

```Code - Java Programming```

``````public class Main {

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);
}
}
}``````
Copy The Code &

Output

cmd
root1 = -0.87+1.30i and root2 = -0.87-1.30i