Program 2
Compute the
roots of a quadratic equation by accepting the coefficients.
Print appropriate messages based on the
discriminant value to determine
if roots are
real and distinct,
real and equal,
or
complex (imaginary).
Algorithm
- Initialize: Start the program
- Input Coefficients: Read coefficients a, b, c from user
- Calculate Discriminant: d = b² - 4ac
- Check Discriminant: Compare d with 0
- If d > 0: Calculate two real and distinct roots
- If d = 0: Calculate one real and equal root
- If d < 0: Display "Roots are imaginary"
- Output: Display appropriate message and roots
- Terminate: Stop the program
Flowchart
START
→
Input a, b, c
→
d = b²-4ac
→
Check d
→
Calculate Roots
→
Display Results
→
STOP
Code
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, d, r1, r2;
printf("Enter coefficients a, b, c: ");
scanf("%f %f %f", &a, &b, &c);
d = b*b - 4*a*c; // discriminant
if (d > 0) {
r1 = (-b + sqrt(d)) / (2*a);
r2 = (-b - sqrt(d)) / (2*a);
printf("Roots are real and distinct: %.2f , %.2f\n", r1, r2);
}
else if (d == 0) {
r1 = r2 = -b / (2*a);
printf("Roots are real and equal: %.2f , %.2f\n", r1, r2);
}
else {
printf("Roots are imaginary (complex).\n");
}
return 0;
}
Replay !
Share Your Thoughts