Home » Programming » C » Quadratic Equation Program in C

Quadratic Equation program in C

In this article, you will learn to find the roots of a quadratic equation in C Language.

The standard form of a quadratic equation is:

ax2 + bx + c = 0, 
where a, b and c are real numbers

The term b2-4ac is known as the discriminant of a quadratic equation. It tells the nature of the roots.

  • If the discriminant is greater than 0, the roots are real and different.
  • If the discriminant is equal to 0, the roots are real and equal.
  • If the discriminant is less than 0, the roots are complex and different.

Addition of two number program in C.

#include <stdio.h>

#include <math.h>

int main()

{

	double a, b, c, discriminant, root1, root2, realPart, imgPart;	

	printf("Enter coefficient a: ");

	scanf("%lf",&a);

	

	printf("Enter coefficient b: ");

	scanf("%lf",&b);

	printf("Enter coefficient c: ");

	scanf("%lf",&c);

	

	discriminant = b * b - 4*a*c;

	

	//Condition for real and equal roots

	if(discriminant == 0)

		{

			root1 = root2 = -b / (2 * a);

			printf("\nFor the coefficients a = %.2lf, b = %.2lf and c = %.2lf \n\nroot1 = root2 = %.2lf", a, b, c, root1 );

			

			

			} 

			

			//Condition for real and different roots

			else if(discriminant > 0) 

				{

					//sqrt function returns square root

					

					root1 = (-b + sqrt(discriminant)) / (2 * a);

					root2 = (-b - sqrt(discriminant)) / (2 * a);

					

					printf("\nFor the coefficients a = %.2lf, b = %.2lf and c = %.2lf \n\nroot1 = %.2lf and root2 = %.2lf", a, b, c, root1, root2);

					}

					

					//Condition for if roots are not real

					else

					{

						realPart = -b / (2 * a);

						imgPart = sqrt(-discriminant) / (2 * a);

						

						

						printf("\nFor the coefficients a = %.2lf, b = %.2lf and c = %.2lf \n\nroot1 = %.2lf + %.2lfi and root2 = %.2lf - %.2lfi", a, b, c, realPart, imgPart, realPart, imgPart);

					}

					

						return 0;

					

	}

						

Output:

Enter coefficient a: 1

Enter coefficient b: 4

Enter coefficient c: 4

For the coefficients a = 1, b = 2 and c = 3

root1 = root2 = -2.00

In this program, the sqrt() library function is used to find the square root of a number.

Note: If you interested lo learn C through web, You can click here

Conclusion:

Hi guys, I can hope that you can know that how to write a Quadratic equation program in C. If you like this post as well as know something new so share this article in your social media accounts. If you have any doubt related to this post then you ask in comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *