Thursday, June 19, 2014

Elementary Programming; Exercise No. 17

Write a program that prompts the user to enter three points  (x1, y1) , (x2, y2) , (x3, y3) of a triangle and displays its area. The formula for computing the area of a triangle is:


Solution:

public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   double x1, y1, x2, y2, x3, y3; // variables to hold the points of the triangle
   double side1, side2, side3; // variables to hold the sides of the triangle
   double s, area;
   System.out.print("Enter x1 and y1:");
   x1 = scanner.nextDouble();
   y1 = scanner.nextDouble();
   System.out.print("Enter x2 and y2:");
   x2 = scanner.nextDouble();
   y2 = scanner.nextDouble();
   System.out.print("Enter x3 and y3:");
   x3 = scanner.nextDouble();
   y3 = scanner.nextDouble();
   side1 = Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);
   side2 = Math.pow(Math.pow(x3 - x1, 2) + Math.pow(y3 - y1, 2), 0.5);
   side3 = Math.pow(Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2), 0.5);
   s = (side1 + side2 + side3)/2;
   area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);
   System.out.print("The area of the triangle is " + area);
}

1 comment:

  1. Thanks a lot. Been searching for the correct formula for finding the length of side of triangle. Your post has even shown how to implement it. Nice!

    ReplyDelete

Author