Exercise:
Write a C Program to find the roots of a quadratic equation.
Click Here to View the Solution!
#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);
}
return 0;
}
Click Here to View the Output!
Enter coefficients a, b and c: 6 12 2
root1 = -0.18 and root2 = -1.82
Click Here to View the Explanation!
- This program is used to determine the roots of a quadratic equation.
- The program requests the user to enter three coefficients
a, b, c
and store them in thedouble type
variables a, b and c using thescanf()
function. - The determinant is then calculated using the formula (b*b – 4*a*c).
If…else if
statements are used to determine the nature of the roots.- If the discriminant is greater than 0 the roots are real and different and are calculated using the formulas (-b + sqrt(discriminant)) / (2 * a) and (-b – sqrt(discriminant)) / (2 * a) and are printed, where
sqrt
is a function for calculating the square root of a number. - If the discriminant is equal to 0, the roots are real and equal and are calculated using the same formula (-b / (2 * a)) and are printed.
- Else, the discriminant would be less than 0, the roots would not be real and the real and imaginary parts of the roots are calculated using the formulas (-b / (2 * a)) and (sqrt(-discriminant) / (2 * a)) and are printed.
- The
return 0 statement
is used to exit the program execution.