Articles

C Program for Quadratic Equation

Share

The program calculates whether a quadratic equation has real roots or imaginary roots.

A quadratic equation is a polynomial equation, having highest degree of two. The equation is represented in the form of ax2+bx+c where a can’t be 0, c is constant, a and b are coefficients. There can be two answers of x which is termed as roots.

This Quadratic formula is applied only when b2– 4ac >= 0.
such that,
If b2– 4ac > 0 , means the eqn. has more than one real roots
if b2– 4ac = 0 , represent equal or single root
if b2– 4ac <0, represents imaginary root
Lastly, if a is 0, then the equation would not be considered as a quadratic equation.

A quadratic equation is an equation having a degree of 2.  There are 4 possibilities, these are real roots, equal roots, imaginary roots and not a quadratic equation.

Steps to calculate quadratic equation

  • Read a, b, c values
  • if a == 0, then it’s not a quadratic equation
  • else,
    calculate result = b2 – 4ac
    • if result > 0 then
      compute the real roots using the formula
      print root1,root2 values
    • Else if result = 0 then
      compute the equal roots using the formula
      print root1,root2 values
    • Else if result < 0 then
      roots are imaginary
      print no solution

C Program for Quadratic Equation

Program:

#include<conio.h>
#include<stdio.h>
#include<math.h>
void main (){
  float a, b, c, result;
  printf (" ax^2 + bx + c, \n enter the values of a, b and c : = ");
  scanf ("%f %f %f", &a, &b, &c);

  result = (b * b) - (4 * a * c);
  if (a == 0)
    printf ("The equation is not a quadratic equation");
  else if (result > 0)
    {
      result = sqrt (result);
      printf ("Real roots are, %f,%f \n", (-b - result) / (2 * a),
        (-b + result) / (2 * a));
    }
  else if (result == 0)
    {
      result = sqrt (result);
      printf ("equal root, %f,%f \n", (-b) / (2 * a), (-b) / (2 * a));
    }
  else
    {
      printf ("Root are imaginary ;\n No Solution");
    }

  getch ();
}

 

Output:

Imaginary Roots or No solution

ax^2 + bx + c, 
 enter the values of a, b and c : = 11 5 5
Root are imaginary ;
 No Solution

Real roots:

 ax^2 + bx + c, 
 enter the values of a, b and c : = 5 5 1
Real roots are, -0.723607,-0.276393 

 

Equal roots:

 ax^2 + bx + c, 
 enter the values of a, b and c : = 5 10 5
equal root, -1.000000,-1.000000 

Not Quadratic

 ax^2 + bx + c, 
 enter the values of a, b and c : = 0 5 5 
The equation is not a quadratic equation

This post was last modified on August 26, 2022

Sandeep Verma

Published by
Sandeep Verma
Tags: C C Program for Quadratic Equation program quadratic equation software testing st