C++ Program to Find Roots of Quadratic Equation using if else

By | 24.12.2016

Roots of Quadratic Equation using if else


Write a C++ Program to Find Roots of Quadratic Equation using if else. Here’s simple C++ Program to Find Roots of Quadratic Equation using if else in C++ Programming Language.


Here is source code of the C++ Program to Find Roots of Quadratic Equation using if else. The C++ program is successfully compiled and run(on Codeblocks) on a Windows system. The program output is also shown in below.


SOURCE CODE : :


/*  C++ Program to Find Roots of Quadratic Equation using if else  */

#include <iostream>
#include <cmath>
using namespace std;

int main()
{

    float a, b, c, x1, x2, determinant, realPart, imaginaryPart;
    cout << "Enter coefficient a :: ";
    cin >> a ;
    cout << "\nEnter coefficient b :: ";
    cin >> b ;
    cout << "\nEnter coefficient c :: ";
    cin >> c ;

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

    if (determinant > 0)
    {
        x1 = (-b + sqrt(determinant)) / (2*a);
        x2 = (-b - sqrt(determinant)) / (2*a);
        cout << "\nRoots are real and different." << endl;
        cout << "\nx1 = " << x1 << endl;
        cout << "\nx2 = " << x2 << endl;
    }

    else if (determinant == 0)
    {
        cout << "\nRoots are real and same." << endl;
        x1 = (-b + sqrt(determinant)) / (2*a);
        cout << "\nx1 = x2 = " << x1 << endl;
    }

    else
    {
        realPart = -b/(2*a);
        imaginaryPart =sqrt(-determinant)/(2*a);
        cout << "\nRoots are complex and different."  << endl;
        cout << "\nx1 = " << realPart << "+" << imaginaryPart << "i" << endl;
        cout << "\nx2 = " << realPart << "-" << imaginaryPart << "i" << endl;
    }

    return 0;
}

Output : : 


/*  C++ Program to Find Roots of Quadratic Equation using if else  */

Enter coefficient a :: 4

Enter coefficient b :: 5

Enter coefficient c :: 1

Roots are real and different.

x1 = -0.25

x2 = -1

Process returned 0

Above is the source code for C++ Program to Find Root of Quadratic Equation using if else which is successfully compiled and run on Windows System.The Output of the program is shown above .

If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.


Thanks for reading the post….

4.5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments