This is the Java Program to Find the Area of a Triangle Using Heron’s formula.
Problem Description
Write a Java Program to Find the Area of a Triangle Using Heron’s formula.
Problem Solution
The area of a triangle can be calulated as (s*(s-a)*(s-b)*(s-c))^(1/2), where s is semi-perimeter of the triangle
s = (a + b + c)/2
.
Program/Source Code
Here is the source code of the Java Program to Find the Area of a Triangle Using Heron’s formula. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Find the Area of a Triangle Using Heron's formula
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HeronsFormula {
// Function to calculate area using Heron's Formula
static void area(double a, double b, double c){
double s = (a+b+c)/2;
s = s*(s-a)*(s-b)*(s-c);
System.out.println("Area of the triangle is " + Math.sqrt(s));
}
// Function to read user input
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double a,b,c;
System.out.println("Enter the three sides of the triangle");
try{
a = Double.parseDouble(br.readLine());
b = Double.parseDouble(br.readLine());
c = Double.parseDouble(br.readLine());
}catch (Exception e){
System.out.println("An error occurred");
return;
}
if(a<0 || b<0 || c<0){
System.out.println("Invalid Input");
return;
}
area(a,b,c);
}
}
Program Explanation
1. In function area(), firstly the semi-perimeter is calculated.
2. Then, the area is calculated using heron’s formula and displayed.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Time Complexity: O(1).
Runtime Test Cases
Case 1 (Simple Test Case): Enter the three sides of the triangle 14 56 43 Area of the triangle is 127.31236192923294
Sanfoundry Global Education & Learning Series – Java Programs..
Check this: Programming Books | BCA MCQs
Next Steps:
- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Java Books
- Practice Programming MCQs
- Apply for Java Internship
- Practice Information Technology MCQs
- Apply for Information Technology Internship