Question:
Write a C Program to find all Roots of a Quadratic Equation
Answer:
The standard form of a quadratic equation is:
ax2 + bx + c = 0, where
a, b and c are real numbers and
a != 0
The term b2-4ac
is known as the discriminant of a quadratic equation. It tells the nature of the roots.
__________________________________________________________________________________
C Language programming code to find root of quadratic equation:
/* C program to find roots of a quadratic equation */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// Prints roots of quadratic equation ax*2 + bx + x
void findRoots(double a, double b, double c)
{
double sqrt_val;
// If a is 0, then equation is not quadratic, but
// linear
if (a == 0) {
printf("Invalid");
return;
}
int d = b * b - 4 * a * c;
sqrt_val = sqrt(abs(d));
//If the discriminant is greater than 0, the roots are real and different.
if (d > 0) {
printf("Roots are real and different \n");
printf("%f\n%f", (-b + sqrt_val) / (2 * a),
(-b - sqrt_val) / (2 * a));
}
//If the discriminant is equal to 0, the roots are real and equal.
else if (d == 0) {
printf("Roots are real and same \n");
printf("%f", -b / (2 * a));
}
//If the discriminant is less than 0, the roots are complex and different.
else // d < 0
{
printf("Roots are complex \n");
printf("%f + i%f\n%f - i%f", -b / (2 * a),
sqrt_val, -b / (2 * a), sqrt_val);
}
}
// Driver code
int main()
{
double a ,b,c;
printf("Enter a, b and c where a*x*x + b*x + c = 0\n");
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
// Function call
findRoots(a, b, c);
return 0;
}
_________________________________________________________
SCREENSHOOT OF RUNNING PROGRAM:
___________________________________________________________________________________
SCREENSHOOT OF OUTPUT WINDOW:
0 Comments: