Java program to find area of triangle
In this post, you will learn how to write the Java program to find the area of a triangle.
There are several ways to calculate the area of a triangle. Here, we will discuss the simplest approach to calculate the area of a triangle in Java.
Find Area of Triangle using Heron's Formula
If we know the size of three sides of a triangle, then we can easily calculate the area of a triangle using Heron's Formula.
Area of a Triangle = √(s*(s-a)*(s-b)*(s-c))
Here, s is semiperimeter, and a, b, c are three sides of a triangle. The semi perimeter is calculated as follows:
s = (a + b + c)/2
Here, the lengths of all three sides of the triangle are given. We are using these values and calculating the semi-perimeter of the triangle, and hence the area of the triangle using Heron's Formula is calculated as.
// Java program to calculate
// the area of triangle
public class AreaTriangle {
public static void main(String[] args) {
// sides of a triangle
double s1, s2, s3;
double sp, triArea;
// three sides of a triangle
s1 = 32.0;
s2 = 31.21;
s3 = 22.52;
// Calculate the semi-perimeter
sp = (s1+s2+s3)/2.0d;
// calculate the area
triArea = Math.sqrt(sp* (sp - s1) * (sp - s2) * (sp - s3));
System.out.println("Area of Triangle : " + triArea);
}
}
Output of the above code:
Area of Triangle : 332.3160104434022
Java Calculate Area of Triangle
The basic formula for the area of a triangle is equal to half the product of its base and height. This formula is applicable to all types of triangles, whether it is a scalene triangle, an equilateral triangle, or an isosceles triangle.
Area = 1/2 (base × height)
In the given example, we allow the user to enter the width and height of the triangle and easily calculate the area of the triangle.
import java.util.Scanner;
public class AreaTriangle {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the width of triangle: ");
double width = scanner.nextDouble();
System.out.println("Enter the height of triangle:");
double height = scanner.nextDouble();
double area = (width* height)/2;
System.out.println("Area of Triangle : " + area);
}
}
Output of the above code:
Enter the width of triangle:
12
nter the height of triangle:
10
Area of Triangle : 60.0
Related Articles
Area of circle program in JavaRemove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Fibonacci series program in Java
Java program to check leap year
Java program to find factorial of a number