In this C program we'll see how to find the Roots of Quadratic Equation using formula:
x = -b+-√D / 2a
here, D = Discriminant = b^2-4ac
- LOGIC:
For this we'll first calculate the discriminant and print the roots if roots are real otherwise we'll print Roots are imaginary. Since, we've to find square root so don't forget to include <math.h> file.
- ALGORITHM:
- Start
- Input the values of a, b and c from the equation: ax^2+bx+c=0
- Calculate discriminant, D=b^2-4ac
- If D>=0 then calculate: x1= -b+√D /2a and x2= -b-√D /2a
- Print roots x1 and x2
- Otherwise, print imaginary roots
- End
- CODE:
#include <stdio.h>
#include <math.h>
int main ()
{
//declare variables
float a, b, c, D, x1, x2;
printf("Enter the values of a, b and c : ");
//input values from user
scanf("%f %f %f",&a,&b,&c);
//calculate discriminant, D
D = (b*b) - (4*a*c);
//check if roots are real or imaginary
if(D>=0)
{
//calculate real roots
x1 = (-b+sqrt(D)) / (2*a);
x2 = (-b-sqrt(D)) / (2*a);
//print real roots
printf("Roots are : x1 = %.2f , x2 = %.2f", x1, x2);
}
//if roots are not real then print imaginary roots
else
{
printf("Roots are Imaginary");
}
return 0;
}
- OUTPUT:
Enter the values of a, b and c : 1 4 4
Roots are : x1 = -2.00 , x2 = -2.00
- CHALLENGE.3:
Try to make a program to find if a student is eligible or not.
Conditions: marks in--
- Math >= 60
- Science >= 65
- English >= 75
That's it for today. If you've any queries, then don't hesitate to comment. Your problem will be solved.
Share, Subscribe and keep coding...
Comments
Post a Comment