Contact Learn C
Copy Program Share Program

Program 18:To find roots of quadratic equation

Program 18:
int main()
  float A, B, C, root1, root2;
  float real, imaginary, discriminant;
  printf("Enter the values of A, B and C\n");
  scanf("%f %f %f", &A,&B,&C);
  if( A==0 || B==0 || C==0)
   printf("Error: Roots cannot be determined\n");
   discriminant = B*B - 4.0*A*C;
   if(discriminant < 0) 
     printf("Imaginary Roots\n"); 
     real = -B/(2.0*A) ; 
     imaginary = sqrt(abs(discriminant))/(2.0*A); 
     printf("Root1 = %f +i %f\n",real, imaginary); 
     printf("Root2 = %f -i %f\n",real, imaginary); 
    else if(discriminant == 0) 
     printf("Roots are real and equal\n"); 
     root1 = -B/(2.0*A); 
     root2 = root1; 
     printf("Root1 = %f \n",root1); 
     printf("Root2 = %f \n",root2); 
    else if(discriminant > 0 )
     printf("Roots are real and distinct\n");
     root1 =(-B+sqrt(discriminant))/(2.0*A);
     root2 =(-B-sqrt(discriminant))/(2.0*A);
     printf("Root1 = %f \n",root1);
     printf("Root2 = %f \n",root2);
  return 0;
  1. As you know a quadratic equation is ax2+bx+c
  2. The program starts with initilizing
    • A-for storing value of a as in ax2+bx+c
    • B-for storing value of b as in ax2+bx+c
    • C-for storing value of c as in ax2+bx+c
  3. Checking whether all values are 0 or not and if any one of them is zero then it will
    • print an error message saying roots can't be determined.
  4. If step 3 is not satisfied then
    • we should calculate discriminant by using formula (d=b2-4ac)
      • If discriminant is less than zero
        • There are no real roots and all are imaginary
        • real part is calculated by using formula real=-b/2a
        • imaginary part is calculated by formula imaginary=√|d|/2a
        • Then printing roots of equation.
      • If discriminant is equal to zero then the roots are Real and Equal
        • roots are calculated by using formula root=-b/2a for both
        • Then printing roots of equation.
      • If discriminant is greater than zero then the Roots are real and distinct
        • root1 is calculated by using formula root1=(-b+√|d|/2a)/2a
        • root2 is calculated by formula root2=(-b-√|d|/2a)/2a
        • Then printing roots of equation.

Find roots of quadratic equation

No comments:

Post a Comment

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide