Algorithm
-
Input:
- i. Prompt the user to enter the coefficients
a
,b
, andc
of a quadratic equation.
- i. Prompt the user to enter the coefficients
-
Calculate Discriminant:
- i. Calculate the discriminant using the formula
discriminant = b*b - 4*a*c
.
- i. Calculate the discriminant using the formula
-
Check Discriminant Value:
- 1. If
discriminant > 0
, there are two real roots. Calculate them using the quadratic formula:ii. root1 = (-b + sqrt(discriminant)) / (2*a)
iii. root2 = (-b - sqrt(discriminant)) / (2*a)
- If
discriminant == 0
, there is one real root (a repeated root). Calculate it using:i. root1 = root2 = -b / (2*a)
- If
discriminant < 0
, roots are imaginary, and the program cannot compute them.
- 1. If
-
Output Roots:
- 1. Print the roots of the equation based on the conditions met:
- i. If two real roots:
printf("The roots of the equation are: %f and %f", root1, root2);
- ii. If one real root:
printf("The roots of the equation are equal and have the value: %f and %f", root1, root2);
- iii. If imaginary roots:
printf("The roots of the equation are imaginary and hence we cannot compute them");
- i. If two real roots:
- 1. Print the roots of the equation based on the conditions met:
Code Examples
#1 Code Example-C Programing Implementation Code
Code -
C Programming
# include<stdio.h>
# include<conio.h>
# include<math.h>
int main (){
float a,b,c;
printf (“Enter the values of coefficient: a, b, and c”);
scanf (“ %f %f %f”, &a, &b, &c);
float discriminant;
discriminant= b*b – 4*a*c;
float root1, root2;
if (discriminant>0){
root1 = -b+sqrt (discriminant) / (2*a);
root2 = -b-sqrt (discriminant) / (2*a);
printf (“The roots of the equation are = %f %f”, r1, r2);
}
else if (discriminant==0){
root1 = -b/(2*a);
root2 = -b/(2*a);
printf (“The roots of the equation are equal having the value =%f %f”, r1, r2);
}
else
printf(“The roots of the equation are imaginary and hence we can not compute them”);
}
Copy The Code &
Try With Live Editor
Output
The roots of the equation are = -1 -3
#2 Code Example-C Programing Find the values of a, b, and c in a quadratic equation
Code -
C Programming
#include<stdio.h>
#include<math.h>
int main(){
float a,b,c;
float d,root1,root2;
printf("Enter the quadratic equation in the format ax^2+bx+c: ");
scanf("%fx^2%fx%f",&a,&b,&c);
float discriminant;
discriminant = b * b - 4 * a * c;
if(discriminant < 0){
printf("Roots are imaginary number.\n");
continue;
}
float root1, root2;
root1 = ( -b + sqrt(discriminant)) / (2* a);
root2 = ( -b - sqrt(discriminant)) / (2* a);
printf("Roots of quadratic equation are: %f and %f",root1,root2>;
}
Copy The Code &
Try With Live Editor
Output
Enter quadratic equation in the format ax^2+bx+c: 2x^2+4x+(-1)
The roots of the quadratic equation are: 0 and -2
The roots of the quadratic equation are: 0 and -2
Demonstration
C Programing Example to Find the Roots of a Quadratic Equation-DevsEnv