Starter Tutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » C Programming » Programs » Others » C program to find the roots of a quadratic equation
Suryateja Pericherla Categories: Others. No Comments on C program to find the roots of a quadratic equation
Join Our Newsletter - Tips, Contests and Other Updates
Email
Name

In this article we will learn to implement a C program to find the roots of a quadratic equation. A C program is provided below for calculating the roots of a quadratic equation ax^2+bx+c=0

 

Program is a follows:

//C program to find the roots of a quadratic equation. Ex: ax^2+bx+c=0
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
	int a, b, c;
	double disc, r1, r2, real, imag;
	printf("Enter values of a, b and c: ");
	scanf("%d%d%d",&a,&b,&c);
	disc=(b*b)-(4*a*c);
	if(disc<0)
	{
		printf("Roots are imaginary...");
		real = -b/(2.0*a);
		imag = sqrt(-disc)/(2.0*a);
		printf("\nRoot r1 is: %d + i %lf",real,imag);
		printf("\nRoot r2 is: %d - i %lf",real,imag);
	}
	else if(disc==0)
	{
		printf("Roots are real and equal...");
		r1=-b/(2.0*a);
		r2=r1;
		printf("\nRoot r1 is: %lf",r1);
		printf("\nRoot r2 is: %lf",r2);
	}
	else
	{
		printf("Roots are real and distinct...");
		r1=(-b+sqrt(disc))/(2.0*a);
		r2=(-b-sqrt(disc))/(2.0*a);
		printf("\nRoot r1 is: %lf",r1);
		printf("\nRoot r2 is: %lf",r2);
	}
	getch();
}

 

Input and output for the above program is as follows:

Enter values of a, b and c: 2 4 2
Roots are real and equal...
Root r1 is: -1.000000
Root r2 is: -1.000000

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory