Develop a program to compute the roots of a quadratic equation by accepting the coefficients.
Print appropriate
messages.
Algorithm:
1. Start.
2. Read the coefficients a, b and c.
3. If a is zero display “Invalid Input”
4. Otherwise,
1. calculate deltab*b-4*a*c
2. If delta is greater than zero
i. r1-b+sqrt(b*b-4*a*c)/(2*a)
ii. r2-b- sqrt(b*b-4*a*c)/(2*a)
iii. Display “Roots are real and distinct”
iv. Display the roots r1 and r2
3. If delta is equal to zero
i. r1=r2=-b/(2*a)
ii. Display “Roots are real and equal”
iii. Display r1 and r2.
4. Otherwise
i. rp-b/(2*a)
ii. ip sqrt(b*b-4*a*c)/(2*a)
iii. Display “Roots are imaginary”
iv. Display the roots
5. End
Test Cases:
Sl Test Data
no. Expected Output
A B c
1 1 4 4 Roots are Real and Equal
Root1=Root2=-2.000000
2 1 -5 6 Roots are Real and Distinct
Root1=3.000000
Root2=2.000000
3 2 3 4 Roots are Real and Imaginary
Root1=-0.750000+i1.198958
Root2=-0.750000-i1.198958
4 1 0 8 Invalid Input
5 0 3 6 Invalid Input
Flowchart:
Start
Read a,b,c
Write T F
“Invalid a==0
Output”
r1=(-b+sqrt(d))/(2*a) T
d>0
r1=(-b-sqrt(d))/(2*a)
Write “roots are F
real”
r1=(-b+sqrt(d))/(2*a) T
d<0
r1=(-b-sqrt(d))/(2*a)
F
Write “roots are
r1=r2=-b/(2*a)
real”
Write “roots are
equall”
stop
Viva Questions:
Sl.NO Questions
1. What is a Quadratic equation?
2. When the roots are equal distinct and imaginary?
3. What are input and output functions?
4. What is the syntax of if and if else condition?
5. What is sqrt function and fabs function?
6. What is math.h header?
7. What is the size of int,float,double,char and void?
Modification Questions:
Sl.NO Questions
1. Implement the same program using switch
2. Find the largest of two numbers?
3. Find the Largest of three numbers
Program:
#include <stdio.h>
#include <math.h>
void main()
{
int a,b,c;
float r1,r2,d,rp,ip,r;
printf("Enter three coefficients\n");
scanf("%d%d%d",&a,&b,&c);
if (a*b*c==0)
printf("Invalid Input\n");
else
{
d=b*b-4*a*c;
r=sqrt(fabs(d));
if (d>0)
{
r1=(-b+r)/(2.0*a);
r2=(-b-r)/(2.0*a);
printf("Roots are Real and Distinct\n");
printf("Root1=%f\nRoot2=%f\n",r1,r2);
} else if (d==0)
{
r1=r2=-b/(2.0*a);
printf("Roots are Real and Equal\n");
printf("Root1=Root2=%f\n",r1);
} else
{
rp=-b/(2.0*a);
ip=r/(2.0*a);
printf("Roots are Real and Imaginary\n");
printf("Root1=%f+i%f\nRoot2=%f-i%f\n",rp,ip,rp,ip);
}
}
getch();
}