Aim
A math app needs to determine the type of roots for a quadratic equation based
on user input. Develop a C program to calculate and display the roots based on
the given coefficients .
Code
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, root1, root2, disc, real, imag;
printf("Enter coefficients of quadratic equation (a, b, c): ");
scanf("%f %f %f", &a, &b, &c);
if (a == 0 && b == 0)
{
printf("Invalid Coefficients! \n");
}
else if (a == 0)
{
// Linear equation bx + c = 0
root1 = - c / b;
printf("Linear Equation with root: %.2f \n", root1);
}
else
{
// Quadratic equation
disc = b * b - 4 * a * c;
printf("Discriminant = %.2f \n", disc);
if (disc > 0)
{
root1 = ( - b + sqrt(disc)) / (2 * a);
root2 = ( - b - sqrt(disc)) / (2 * a);
printf("Two distinct real roots: %.2f and %.2f \n", root1, root2);
}
else if (disc == 0)
{
root1 = - b / (2 * a);
printf("One real root: %.2f \n", root1);
}
else
{
real = - b / (2 * a);
imag = sqrt( - disc) / (2 * a);
printf("Complex roots: %.2f + %.2fi and %.2f - %.2fi\n", real, imag, real, imag);
}
}
return 0;
}
Algorithm
Step1: Start
Step2: Input the coefficients a, b, and c of the quadratic equation.
Step3: Check if a == 0 and b == 0:
If true, print "Invalid Coefficients" and terminate the program.
Step4: Else if a == 0:
i. The equation is linear (bx + c = 0).
ii. Calculate root = - c / b.
iii. Print the linear root and terminate the program.
Step5: Else (a ≠ 0):
1. The equation is quadratic.
2. Calculate the discriminant: disc = b² - 4ac.
3. Print the discriminant.
4. If disc > 0:
i. Calculate two real and distinct roots:
ii. root1 = ( - b + sqrt(disc)) / (2a)
iii. root2 = ( - b - sqrt(disc)) / (2a)
iv. Print both roots.
Else if disc == 0:
i. Calculate one real and repeated root:
ii. root = - b / (2a)
iii. Print the root.
Else (disc < 0):
i. Calculate complex roots:
ii. real = - b / (2a)
iii. imag = sqrt( - disc) / (2a)
iv. Print the complex roots in the form real ± imag i.
Step6: Stop
Flow chart