### Archive

Archive for January 1, 2010

## C++ Program to find Roots (Real & Complex) of a Quadratic Equation – Q1

Q1. Program to find Roots (Real & Complex) of a Quadratic Equation:

… from College notes (BCA/MCA assignments):

```#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <complex.h>

void main(){
int aint, bint, cint, b2, dsq;
float rt1 , rt2, d;
clrscr();

cout<<"\n\t a*x^2 + b*x + c";

cout<<"\n Enter the Value of a: ";
cin>>aint;

cout<<"\n Enter the Value of b: ";
cin>>bint;

cout<<"\n Enter the Value of c: ";
cin>>cint;

b2 = pow(bint, 2);
d = b2 - 4 *  aint * cint;

if(d > 0){
dsq = sqrt(d);
rt1 = (-bint + dsq) / (2 * aint);
rt2 = (-bint - dsq) / (2 * aint);
cout<<"\n Roots are Real and distinct";
}
else if(d == 0){
rt1 = -bint/2 * aint;
rt2 = rt1;
cout<<"\n Roots are Real and same";
}
else {
rt1 = -bint/2 * aint;
rt2 = sqrt(-bint)/2 * aint;
cout<<"\n Roots are Complex and distinct";
}

cout<<"\n rt1 : "<<rt1;
cout<<"\n rt2 : "<<rt2;

getch();
}
```

Output:

Equation is:-

a*x^2 + b*x + c

Enter the Value of a: 3

Enter the Value of b: 4

Enter the Value of c: 5

Roots are:-
rt1 : 9.476982e-41
rt2 : 219.999786

Categories: Cpp