Q.Write a C program to find the root of the given quadratic equation using the conditional (if-else) case.
The textbook presents this worked program, transcribed exactly as printed (including its printed errors):
/*program to find the root of the quadratic equation*/
#include<stdio.h>
#include<math.h>
void main()
{
floata,b,c,discrmnt,x-imag-1,x-imag-2,x-real-1,x-real-2,temp;
scanf("%f%f%f",&a,&b,&c);
printf("a=%f,b=%f,c=%f\n",a,b,c);
discrmnt=b*b-4.0*a*c;
if(discrmnt<0)
{
discrmnt=-discrmnt;
x-imag-1=sqrt(discrmnt)/(2.0*a);
x-imag-2=x-imag-1;
x-real-1=-b(2.0*a);
printf("complex conjugate roots\n");
printf("realpart=%16.8e\n",x-real-1);
printf("imaginarypart=%16.8e\n",x-imag-1);
}
else
{
if(discrmnt==0)
{
x-real-1=-b/(2.0*a);
printf("Repeated roots\n");
printf("Real roots=%16.8e\n",x-real-1);
}
else
{
temp=sqrt(discrmnt);
x-real-1=(-b+temp)/(2.0*a);
x-real-2=(-b-temp)/(2.0*a);
printf("Real roots\n");
printf("Real root-1=%16.8e\n",x-real-1);
printf("Real root-2=%16.8e\n",x-real-2);
}
}
} /*End of main*/
/*program to find the root of the quadratic equation*/
#include<stdio.h>
#include<math.h>
void main()
{
floata,b,c,discrmnt,x-imag-1,x-imag-2,x-real-1,x-real-2,temp;
scanf("%f%f%f",&a,&b,&c);
printf("a=%f,b=%f,c=%f\n",a,b,c);
discrmnt=b*b-4.0*a*c;
if(discrmnt<0)
{
discrmnt=-discrmnt;
x-imag-1=sqrt(discrmnt)/(2.0*a);
x-imag-2=x-imag-1;
x-real-1=-b(2.0*a);
printf("complex conjugate roots\n");
printf("realpart=%16.8e\n",x-real-1);
printf("imaginarypart=%16.8e\n",x-imag-1);
}
else
{
if(discrmnt==0)
{
x-real-1=-b/(2.0*a);
printf("Repeated roots\n");
printf("Real roots=%16.8e\n",x-real-1);
}
else
{
temp=sqrt(discrmnt);
x-real-1=(-b+temp)/(2.0*a);
x-real-2=(-b-temp)/(2.0*a);
printf("Real roots\n");
printf("Real root-1=%16.8e\n",x-real-1);
printf("Real root-2=%16.8e\n",x-real-2);
}
}
} /*End of main*/
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →[!TLDR]
A nested if-else on the discriminant prints complex, repeated or real roots in %16.8e form; a=1,b=-5,c=6 gives 3 and 2.
This solves the same problem as the switch version but branches with if / else if / else on the sign of the discriminant b^2 - 4ac. A negative discriminant means complex roots, so its magnitude is used to form the imaginary part sqrt(|d|)/(2a) with real part -b/(2a); a zero discriminant gives a single repeated root -b/(2a); a positive discriminant gives the two real roots (-b +/- sqrt(d))/(2a). The %16.8e edit descriptor prints each value in scientific (exponential) notation in a 16-wide field with 8 digits after the point. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.