Skip to content
Home » C program to solve the quadratic equation

C program to solve the quadratic equation

Learn about C program to solve the quadratic equation in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

C program to solve the quadratic equation

A quadratic equation is a second-degree equation, which means it contains at least one squared element. The quadratic equation has the conventional form ax2 + bx + c = 0, where a, b, and c are real and a!=0, and x is an unknown variable.

Source code:

#include<stdio.h>
#include<math.h>
int main()
{
   int a, b, c, d;
   int root1, root2, realPart, imaginaryPart;

   printf("Enter cofficients a, b, c: ");
   scanf("%d %d %d", &a, &b, &c);

   d = (b*b) - 4*a*c; //discriminant

   if( d>1 )
   {
     root1 = (-b+sqrt(d)) / 2*a;
     root2 = (-b-sqrt(d)) / 2*a;
     printf("Roots are %d , %d\n", root1, root2);
   }
   else if(d==0)
   {
     root1 = root2 = -b/2*a;
     printf("Roots are %d , %d\n", root1, root2);
   }
   else
   {
     realPart = -b/2*a;
     imaginaryPart = sqrt(d)/2*a;
     printf("root1 = %d + i(%d)\n", realPart, imaginaryPart);
     printf("root1 = %d - i(%d)\n", realPart, imaginaryPart);
   }
   return 0;
}

Output:

Enter cofficients a, b, c: 1 -12 36

Roots are 6 , 6

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Codes :
C program to check odd or even using bitwise operator
Even or odd program without using modulus operator in C