- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to write a C program to find the roots of a quadratic equation?
Problem
Applying the software development method to solve any problem in C Language.
Solution
- Find roots of a quadratic equation, ax2+bx+c.
- There will be 2 roots for given quadratic equation.
Analysis
Input − a,b,c values
Output − r1, r2 values
Procedure
$r_{1}=\frac{-b+\sqrt{b^2-4ac}}{2a}$
$r_{2}=\frac{-b-\sqrt{b^2-4ac}}{2a}$
Design (Algorithm)
- Start
- Read a, b, c values
- Compute d = b2 4ac
- if d > 0 then
- r1 = b+ sqrt (d)/(2*a)
- r2 = b sqrt(d)/(2*a)
- Otherwise if d = 0 then
- compute r1 = -b/2a, r2=-b/2a
- print r1,r2 values
- Otherwise if d < 0 then print roots are imaginary
- Stop
Implementation Code
# include<stdio.h> # include<math.h> int main () { float a,b,c,r1,r2,d; printf ("Enter the values of a b c: "); scanf (" %f %f %f", &a, &b, &c); d= b*b - 4*a*c; if (d>0) { r1 = -b+sqrt (d) / (2*a); r2 = -b-sqrt (d) / (2*a); printf ("The real roots = %f %f", r1, r2); } else if (d==0) { r1 = -b/(2*a); r2 = -b/(2*a); printf ("Roots are equal =%f %f", r1, r2); } else printf("Roots are imaginary"); return 0; }
Testing
Case 1:
Enter the values of a b c: 1 4 3
The real roots = -3.000000 -5.000000
Case 2:
Enter the values of a b c: 1 2 1
Roots are equal =-1.000000 -1.000000
Case 3:
Enter the values of a b c: 1 1 4
Roots are imaginary
Advertisements