Program Statement: Write a JAVA program to find roots of a Quadratic Equation. If Discriminant is negative, display a message stating that there are no real solutions.
Java Program Image

Tested on:

Software: Windows 8, Jdk 1.6,   Netbeans IDE

Hardware: Intel Core i3, 4 GB RAM, 500 GB HDD




Source Code

@Author: Praveen Kanwar
import java.util.*;
class QuadraticRoots
{
   public static void main(String[] args)
    {
        int a,b,c,d;
        Scanner sn=new Scanner(System.in);
        System.out.println("Enter a,b,c values: ");
        a=sn.nextInt();
        b=sn.nextInt();
        c=sn.nextInt();
        d=b*b-4*a*c;
        if(d>0)
        {
            System.out.println("Roots are real and distinct");
            System.out.println("Roots are:");
            double r1=((-b)+Math.sqrt(d))/(2*a);
            double r2=((-b)-Math.sqrt(d))/(2*a);
            System.out.println("r1= "+r1);
            System.out.println("r2= "+r2);
           
           
        }
        else if(d==0)
        {
             System.out.println("Roots are real and equal");
            System.out.println("Roots are:");
            double r1=(-b)/(2*a);
            double r2=(-b)/(2*a);
            System.out.println("r1= "+r1);
            System.out.println("r2= "+r2);
        }
        else
            System.err.println("Roots are imaginary!");
    }
}

Output

CASE 1:
Enter a,b,c values:
1 2 3
Roots are imaginary!
CASE 2:
Enter a,b,c values:
1 5 6
Roots are real and distinct
Roots are:
r1= -2.0
r2= -3.0

Post a Comment

 
Top