Monday, 17 August 2015

Program to find roots of quadratic equation using switch statement

/* Program to find the roots of a quadratic equtaion using switch statement */
#include<stdio.h>
#include<math.h>
main()
{
    int flag;
    float x, x1, x2;
    float a, b, c, d;
    float rpart, ipart;
    clrscr();
    printf("\n Enter 3 numbers: ");
    scanf("%f %f %f", &a, &b, &c);
    if(a==0)
   {
      x=-b/c;
      printf("\n Only root x : %7.3f", x);
      exit();
   }
   d=b*b-4*a*c;
   if(d>0)
       flag=1;
   else if(d==0)
      flag=2;
   else
      flag=3;

   switch(flag)
   {
      case 1:
          printf("\n Real & Distinct roots are: ");
          x1=(-b+sqrt(d))/(2*a);
          x2=(-b-sqrt(d))/(2*a);
          printf("\n x1=%7.3f \n x2=%7.3f", x1, x2);
          break;
      case 2:
          printf("\n Repeated roots are: ");
          x1=-b/(2*a);
          x2=x1;
          printf("\n x1 & x1 : %7.3f", x1);
          break;
      case 3:
          d=sqrt(abs(d));
          rpart=-b/(2*a);
          ipart=d/(2*a);
          printf("\n Complex Roots are: ");
          printf("\n x1=%7.3f+i%7.3f", rpart, ipart);
          printf("\n x2=%7.3f-i%7.3f", rpart, ipart);
    }
    getch();
    return;
}

No comments:

Post a Comment