Write a program to determine the roots of quadratic equation | PPS Program No.3
Write a program to determine the roots of quadratic equation.
Code
#include <stdio.h>
#include <math.h>
int main()
{
int a, b, c, d, x1 , x2, x, e;
printf("Enter the coefficient of X^2 :: a = ");
scanf("%d", &a);
printf("Enter the coefficient of X :: b = ");
scanf("%d", &b);
printf("Enter the constant :: c = ");
scanf("%d", &c);
printf("Quadratic Equation :: %dx^2 + %dx + %d = 0\n", a,b,c);
d = b*b - 4*a*c;
if(d>0)
{
x1 = (-b + sqrt(d))/2*a;
x2 = (-b - sqrt(d))/2*a;
printf("Roots are :: x1= %d and x2 = %d", x1,x2);
}
else if(d==0)
{
x = -b/2*a;
printf("Roots are same x1 = x2 = %d", x);
}
else
{
d= d*-1;
e = 2*a;
printf("Roots are :: x1 = (-%d + √%di)/%d and x2 = (-%d - √%di)/%d ", b,d,e,b,d,e);
}
return 0;
}
Description
A quadratic equation is an equation of the form ax² + bx + c = 0
, where a
, b
, and c
are constants, and x
is the variable. Finding the roots of a quadratic equation involves determining the values of x
that satisfy the equation.
There are several methods for finding the roots of a quadratic equation, including factoring, completing the square, and using the quadratic formula. In this blog, we will focus on writing a program to determine the roots of a quadratic equation using the quadratic formula.
The quadratic formula is given by:
x = (-b ± sqrt(b² - 4ac)) / 2a
where ±
means plus or minus, and sqrt
means square root.
To write a program to determine the roots of a quadratic equation, we can take the following steps:
Step 1: Input the values of a
, b
, and c
from the user.
Step 2: Calculate the discriminant, b² - 4ac
.
Step 3: Check if the discriminant is positive, negative, or zero. If the discriminant is positive, the quadratic equation has two distinct real roots. If the discriminant is zero, the quadratic equation has one real root (a “double root”). If the discriminant is negative, the quadratic equation has two complex roots.
Step 4: Calculate the roots of the quadratic equation using the quadratic formula.
Step 5: Output the roots to the user.
Full Code is Mentioned above. Let’s test the program with some sample inputs:
Output
Example 1:
Enter the coefficient of X^2 :: a = 1
Enter the coefficient of X :: b = -5
Enter the constant :: c = 6
Quadratic Equation :: 1x^2 + -5x + 6 = 0
Roots are :: x1= 3 and x2 = 2
Example 2:
Enter the coefficient of X^2 :: a = 1
Enter the coefficient of X :: b = -6
Enter the constant :: c = 9
Quadratic Equation :: 1x^2 + -6x + 9 = 0
Roots are same x1 = x2 = 3
Example 3:
Enter the coefficient of X^2 :: a = 2
Enter the coefficient of X :: b = 3
Enter the constant :: c = 4
Quadratic Equation :: 2x^2 + 3x + 4 = 0
Roots are :: x1 = (-3 + √23i)/4 and x2 = (-3 - √23i)/4
Watch detailed Explanation through this video.