Friday, 17 April 2015

C++ Program for Solving a Quadratic Equation

AIM

Write and execute a C++ program to solve the quadratic equations.

  • X2-10x+24=0
  •  X2-10x+25=0
  •  X2-10x+30=0

PROGRAM

#include<iostream>
#include<math.h>        // for sqrt()
#include<stdlib.h>     // for abs()
using namespace std;
int main()
{
float a,b,c,r1,r2,d,r,i1,i2,d1;
char ans;
start:                     // label
cout<<"\n\nEnter the three coefficients a,b & c:";
cin>>a>>b>>c;
d=(b*b)-(4*a*c);
if(d<0)
{
cout<<"\n\nThe roots are imaginary\n";
d1=abs(d);
i1=-b/(2*a);
i2=sqrt(d1)/(2*a);
cout<<"\nRoot i1 = "<<i1<<"+i x "<<i2;
cout<<"\nRoot i2 = "<<i1<<"-i x "<<i2<<"\n";
}
else if(d==0)
{
r=-b/(2*a);
cout<<"\n\nThe roots are real and equal\n"<<"\nRoot="<<r<<"\n";
}
else
{
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
cout<<"\nThe roots are real and distinct\n"<<"\nRoot r1="<<r1<<"\nRoot r2="<<r2<<"\n";
}
cout<<"\n\nWould you like to run program again?(y/n):";
cin>>ans;
if(ans=='y')
goto start;              // goto label ‘start’
else
return(0);
}




OUTPUT

Enter the three coefficients a,b & c:1
-10
24

The roots are real and distinct

Root r1=6
Root r2=4


Would you like to run program again?(y/n):y


Enter the three coefficients a,b & c:1
-10
25


The roots are real and equal

Root=5


Would you like to run program again?(y/n):y


Enter the three coefficients a,b & c:1
-10
30


The roots are imaginary

Root i1 = 5+i x 2.23607
Root i2 = 5-i x 2.23607


Would you like to run program again?(y/n):n




Tags:
MG University Practical Exam, Quadratic Equation, C++

No comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...