Introduction: Quadratic Equation Solver in C

About: Moving fast and breaking things!

A quadratic equation is 2nd order polynomial equation that comprises of one variable.

Here is the form of a quadratic equation: ax^2 + bx + c = 0

Note: a, b, c are constants.

It is crucial to note that the coefficient a cannot equal to zero, because a quadratic equation is a 2nd order polynomial. Finding the solutions of a quadratic can be achieved by completing the squares. Also, the solutions of a quadratic equation can either be real or complex. The attached figure shows the quadratic formula and the formulas needed to find its roots (solutions).

We only need a computer and a compiler.

Recommended free compilers:

For Mac: Xcode

For Windows: Microsoft Visual Studio

Step 1: The Code & Testing Various Scenarios

The code is pasted below, and its original file is attached above. Also, the attached figures show the results of various scenarios.

// Copyright © 2016 Talal. All rights reserved.

#include

#include

// this library must be included in order to use built in mathematical functions

int main()

{

while (1)

{

//remind the user of the quadratic equation format

printf("Quadratic Equation format: aX^2 + bX + c \n");

// declare inputs and outputs and their types

float a, b, c, determinant, x1, x2, realSolution, imaginarySolution;

// take the inputs from the user

printf("Enter the coefficients a, b, c respectively seperated by a comma \n");

scanf("%f, %f, %f", &a, &b, &c);

if (a == 0)

{

printf("This is not a quadratic equation \n");

break;

}

// calculate the determinant to determine the number and the type of the solutions

determinant = ((b*b) - (4 * a* c));

printf(" Determinant = %f \n", determinant);

if (determinant == 0)

{

// if the determinant is zero, then there will be one solution

x1 = x2 = (-b)/(2*a);

printf("One real solution and it is %0.1f \n", x1);

}

else if (determinant > 0)

{

x1 = ((-b) + sqrtf(determinant))/(2*a);

x2 = ((-b) - sqrtf(determinant))/(2*a);

printf("Two distinct real solutions and they are %0.1f, and %0.1f \n", x1, x2);

}

else

{

// finally, if the determinant is negative, then the solutions will contain an imaginary part

realSolution = -b /(2*a);

imaginarySolution = sqrtf(-determinant)/(2*a);

printf(" Complex Solutions, and they are %0.1f + %0.1fi and %0.1f - %0.1fi \n", realSolution, imaginarySolution, realSolution, imaginarySolution);

}

}

}

Step 2: Conclusion

YOU MADE IT!

We have successfully written the C code to solve any quadratic equation.

Please feel free to post any questions regarding this instructable in the comments section below.

Also, here are the links to some of my other instructables:

1. Digital Logic Gates (Part 1)

2. Digital Logic Gates (Part 2)

3. NOT, AND, OR Gates using NAND Gates

4.Building Logic Gates Using NPN Transistors (Part 1)

Feel free to check them out.