Java Program to find Roots of Quadratic Equation

Source Code of Java Program to find Roots of Quadratic Equation :

import java.lang.Math;
import java.util.Scanner;

class RootsOfQuadraticEquation
{
   public static void main(String[] args)
   {
     Scanner in = new Scanner(System.in);

     int a, b, c, d;
     double x1, x2;

     System.out.println("Program to find roos of quadratic eq");
     System.out.println("Enter values for ax^2 + bx + c...");

     System.out.print("Enter value for a: ");
     a = in.nextInt();

     System.out.print("Enter value for b: ");
     b = in.nextInt();

     System.out.print("Enter value for c: ");
     c = in.nextInt();

     System.out.println("\n");

     if (a==0)
       System.out.println
         ("Not a quadratic equation.");

     else
     {
       d = (b*b)-(4*a*c);

       if (d>0)
       {
         System.out.println
         ("Real and Distinct Roots.");
         x1=(-b + Math.sqrt(d))/(2*a);
         x2=(-b - Math.sqrt(d))/(2*a);

         System.out.println
           ("Root 1 = " + x1);
         System.out.println
           ("Root 2 = " + x2);
       }

       else
       {
         if (d==0)
         {
           System.out.println
           ("Real and Equal Roots.");
           x1 = x2 = -b/(2*a);
           System.out.println
             ("Root 1 = " + x1);
           System.out.println
             ("Root 2 = " + x2);
         }
         else
         {
           System.out.println
             ("Imaginary Roots.");
           x1 = -b/(2*a);
           x2 = Math.sqrt(-d)/(2*a);
           System.out.println
           ("Root 1 = "+x1+" + i"+x2);
           System.out.println
           ("Root 2 = "+x2+" - i"+x2);
         }
       }
     }
   }
}

Output of Java Program to find Roots of Quadratic Equation 

 

 

0 comments:

Post a Comment