Quadratic Equation Program
quadratic.cpp
Download file: Windows | macOS | Unix
1// Program : Quadratic Equation
2// Author : Prof. Krofchok
3// Date : Fall 2025
4// Description: This program solves quadratic equations having real roots.
5
6#include <cmath> // provides 'sqrt' module
7#include <iostream>
8
9void welcome();
10void input_data(double &a, double &b, double &c);
11void perform_calculations(double a, double b, double c,
12 double &root1, double &root2);
13void output_results(double a, double b, double c,
14 double root1, double root2);
15
16int main()
17{
18 double a, b, c; // coefficients of Ax^2 + Bx + C = 0
19 double root1, root2; // roots of the equation
20
21 welcome();
22 input_data(a, b, c);
23 perform_calculations(a, b, c, root1, root2);
24 output_results(a, b, c, root1, root2);
25}
26
27//
28// An output module that displays information about the program.
29//
30void welcome()
31{
32 std::cout << "This program computes and displays the" << std::endl;
33 std::cout << "roots of a second-degree polynomial" << std::endl;
34 std::cout << "equation of the form Ax^2 + Bx + C = 0." << std::endl;
35 std::cout << std::endl;
36 std::cout << "You will be prompted to input the three" << std::endl;
37 std::cout << "coefficients A, B, and C." << std::endl;
38 std::cout << std::endl;
39 std::cout << "This program acts unpredictably when" << std::endl;
40 std::cout << "given coefficients that do not produce" << std::endl;
41 std::cout << "real-valued roots." << std::endl;
42 std::cout << std::endl;
43}
44
45//
46// An input module that gets the coefficients of a second-degree polynomial
47// in the form Ax^2 + Bx + C
48//
49void input_data(double &a, double &b, double &c)
50{
51 std::cout << "Enter coefficient 'A': ";
52 std::cin >> a;
53 std::cout << "Enter coefficient 'B': ";
54 std::cin >> b;
55 std::cout << "Enter coefficient 'C': ";
56 std::cin >> c;
57}
58
59//
60// A processing module that computes the real-valued roots of the equation,
61// given its coefficients.
62//
63void perform_calculations(double a, double b, double c,
64 double &root1, double &root2)
65{
66 double discriminant;
67
68 discriminant = (b * b) - (4 * a * c);
69 root1 = (-b + sqrt(discriminant)) / (2 * a);
70 root2 = (-b - sqrt(discriminant)) / (2 * a);
71}
72
73//
74// An output module that displays the equation and its roots.
75//
76void output_results(double a, double b, double c,
77 double root1, double root2)
78{
79 std::cout << std::endl;
80 std::cout << "The roots of the equation "
81 << a << "x^2 + "
82 << b << "x + "
83 << c << std::endl;
84 std::cout << "are " << root1 << " and " << root2 << std::endl;
85}