Description
Area of triangle can be calculated using Heron's formula. In geometry, Heron's formula gives the area of a triangle when the length of all three sides are known. The triangle exists if the sum of any of its two sides is greater than the third side.
C/C++
/* C Program to calculate area of triangle */ //Save it as AreaTriangle.c #include<stdio.h> #include<math.h> int main(){ float side1, side2, side3, area, s; printf("Enter the sides of triangle : "); scanf("%f%f%f",&side1,&side2,&side3); // Length of sides must be positive //The triangle exists if the sum of any of its two sides is greater than the third side. if (side1<0 || side2<0 || side3<0 || (side1+side2 <= side3) || side1+side3 <=side2 || side2+side3 <=side1){ printf("Area cannot be calculated"); } else{ //Calculate semiperimeter s = (side1+side2+side3)/2; //Calaculate area area = sqrt(s*(s-side1)*(s-side2)*(s-side3)); printf("Area : %.3f",area); } return 0; }
Input: Enter the sides of triangle : 3 4 5 Output: Area : 6.000
Java
/* Java Program to calculate area of triangle */ //Save it as AreaTriangle.java import java.io.*; import java.util.Scanner; public class AreaTriangle { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); float side1, side2, side3, area, s; System.out.println("Enter the sides of triangle : "); side1 = scanner.nextFloat(); side2 = scanner.nextFloat(); side3 = scanner.nextFloat(); // Length of sides must be positive //The triangle exists if the sum of any of its two sides is greater than the third side. if (side1<0 || side2<0 || side3<0 || (side1+side2 <= side3) || side1+side3 <= side2 || side2+side3 <= side1){ System.out.println("Area cannot be calculated"); } else{ //Calculate semiperimeter s = (side1+side2+side3)/2; //Calaculate area area = (float) Math.sqrt(s*(s-side1)*(s-side2)*(s-side3)); System.out.println("Area : " + area); } } }
Input: Enter the sides of triangle : 3 4 5 Output: Area : 6.0
Related Programs
1) Program to calculate area of a circle2) Program to calculate Area Of right angle triangle
3) Program to calculate area of square
4) Program to calculate area of a Rectangle
5) Program to calculate volume and surface area of cube
6) Program to calculate volume and surface area of cylinder
7) Program to calculate Volume and Surface Area of Sphere