Skip to content
Solved Examples · Example 37

Q.Write a C program to find the root of the given quadratic equation using the switch-case statement. 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<conio.h>  
#include<math.h>  
voidmain()  
{  
    int choice;  
    float a,b,c,d,i,rpart,ipart,r1,r2;  
    clrsc();  
    printf("Enter the value of a,b,c\n");  
    scanf("%f%f%f",&a,&b,&c);  
    d=b*b-4*a*c;  
    if(d>0)  
    }  
        choice=1;  
    {  
    else  
    if(d==0)  
    }  
        choice=2;  
    {  
    else  
    }  
        choice=3;  
    {  
    switch(choice)  
    {  
        case 1:printf("The roots are real and unequal\n");  
            r1=(-b+sqrt(d))/(2*a);  
            r2=(-b-sqrt(d))/(2*a);  
            printf("r1=%.3f\n  r2=%.3f",r1,r2);  
            break;  
        case 2:printf("The roots are equal\n");  
            r1=-b/(2*a);  
            r2=r1  
            printf("r1andr2are%.3f\n",r1);  
            break;  
        case 3:printf("The roots are imaginary\n");  
            d=dqrt(abs(d));  
            rpart=-b/(2*a);  
            ipart=d/(2*a);  
            printf("r1=%.3f+i%.3f\n",rpart,ipart);  
            printf("r2=%.3f-i%.3f\n",rpart,ipart); }  
    }  
    getch();  
}  
Sample output printed in the textbook:
Enter the value of a, b, c  
a = 1, b = 5, c = 2  
r1 = 0.500, r2 = 4.500  
a = 1, b = -2, c = 1  
r1 = r2 = 2  
a = 2, b = 2, c = 5  
r1 = -2+i6, r2 = -2-i6  

Karnataka PUCTextbookLongImportance★★★★★est
99% · 153/154 Questions
🔒 Locked · start free trial →

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 switch on the discriminant prints the roots; correct results are (-0.438, -4.562), (1.000, 1.000) and (-0.5 +/- i1.5).

As in the previous problem, the discriminant d = b^2 - 4ac selects the case: real and unequal roots (-b +/- sqrt(d))/(2a) when d > 0, a repeated root -b/(2a) when d = 0, and a complex conjugate pair with real part -b/(2a) and imaginary part sqrt(|d|)/(2a) when d < 0. Working each printed test case: for a=1, b=5, c=2, d = 25 - 8 = 17 gives r1 = (-5 + 4.123)/2 = -0.438 and r2 = (-5 - 4.123)/2 = -4.562; for a=1, b=-2, c=1, d = 0 gives the repeated root -(-2)/2 = 1; for a=2, b=2, c=5, d = -36 gives real part -2/4 = -0.5 and imaginary part 6/4 = 1.5. …

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.