Basic C Program to find Roots of a quadratic equation

    In this C program we'll see how to find the Roots of Quadratic Equation using formula:

    x = -b+-√D  / 2a

here, D = Discriminant = b^2-4ac


Basic C program to find roots of a quadratic equation

  • LOGIC:

For this we'll first calculate the discriminant and print the roots if roots are real otherwise we'll print Roots are imaginary. Since, we've to find square root so don't forget to include <math.h>  file.


  • ALGORITHM:
  1. Start
  2. Input the values of a, b and c from the equation: ax^2+bx+c=0
  3. Calculate discriminant, D=b^2-4ac
  4. If D>=0 then calculate: x1= -b+√D /2a and x2= -b-√D /2a
  5. Print roots x1 and x2
  6. Otherwise, print imaginary roots
  7. End
  • CODE:
#include <stdio.h>
#include <math.h>

int main ()
{
  //declare variables
  float abcDx1x2;
  printf("Enter the values of a, b and c : ");
  //input values from user
  scanf("%f %f %f",&a,&b,&c);

  //calculate discriminant, D
  D = (b*b) - (4*a*c);

  //check if roots are real or imaginary
  if(D>=0)
  {
    //calculate real roots
    x1 = (-b+sqrt(D)) / (2*a);
    x2 = (-b-sqrt(D)) / (2*a);
    //print real roots
    printf("Roots are : x1 = %.2f , x2 = %.2f"x1x2);
  }
  //if roots are not real then print imaginary roots
  else
  {
    printf("Roots are Imaginary");
  }
  
  return 0;
}

 

  • OUTPUT:

Enter the values of a, b and c : 1 4 4
Roots are : x1 = -2.00 , x2 = -2.00

 

  • CHALLENGE.3:

Try to make a program to find if a student is eligible or not.

Conditions: marks in--

  1.  Math >= 60
  2.  Science >= 65
  3.  English >= 75

That's it for today. If you've any queries, then don't hesitate to comment. Your problem will be solved.

Share, Subscribe and keep coding...

Comments