DEV Community

Cover image for JavaScript Program to solve Quadratic Equation.
Folarin Lawal
Folarin Lawal

Posted on

5 5

JavaScript Program to solve Quadratic Equation.

In this example, you will learn to write a program that solves a quadratic equation in JavaScript.

To understand this example, you should have the knowledge of the following JavaScript programming topics:

  1. JavaScript if...else Statement
  2. JavaScript Math sqrt()

This program computes roots of a quadratic equation when its coefficients are known.

The standard form of a quadratic equation is:

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

To find the roots of such equation, we use the formula,

(root1,root2) = (-b ± √b2-4ac)/2

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.

let userInput = prompt("Input a Number")
for (let a = 0; a <= userInput; a++) {
console.log(a)

}

//QUADRATIC FORMULA FUNCTION

let minus, plus;

let a = prompt("Enter the value for A:");
let b = prompt("Enter the value for B:")
let c = prompt("Enter the value for C:")

let squareRoot = (b*b) - (4*a*c);

// Conditions for Minus or Plus

if (squareRoot > 0) {
minus = (-b - Math.sqrt(squareRoot))/(2 * a);
plus = (-b + Math.sqrt(squareRoot))/(2 * a);

//Result
alert(`The roots of the Quadratic Equation ${minus} and ${plus}`);
Enter fullscreen mode Exit fullscreen mode

}
else if(squareRoot == 0) {
minus = (-b - 0 / (2 * a));
plus = (-b + 0 / (2 * a));

//result
alert(`The roots of the Quadratic Equation are ${minus} and ${plus}`);
Enter fullscreen mode Exit fullscreen mode

}

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay