You are here

C program to find area of a triangle

C program to find area of a triangle: C programming code to calculate area of a triangle using Heron's or Hero's formula. User will enter the lengths of sides of the triangle. Remember for a triangle to exist the sum of any two sides of a triangle must be greater than the third side.

C programming code

  1. /* Assuming triangle exists - valid input from user */
  2.  
  3. #include<stdio.h>
  4. #include<math.h>
  5.  
  6. int main()
  7. {
  8.    double a, b, c, s, area;
  9.    
  10.    printf("Enter the sides of triangle\n");
  11.    
  12.    scanf("%lf%lf%lf", &a, &b, &c);
  13.    
  14.    s = (a+b+c)/2;
  15.    
  16.    area = sqrt(s*(s-a)*(s-b)*(s-c));
  17.    
  18.    printf("Area of the triangle = %.2lf\n", area);
  19.    
  20.    return 0;
  21. }

C program to find area of a triangle using a function

  1. #include<stdio.h>
  2. #include<math.h>
  3.  
  4. double area_of_triangle(double, double, double);
  5.  
  6. int main()
  7. {
  8.    double a, b, c, area;
  9.    
  10.    printf("Enter the lengths of sides of a triangle\n");
  11.    
  12.    scanf("%lf%lf%lf", &a, &b, &c);
  13.    
  14.    area = area_of_triangle(a, b, c);
  15.    
  16.    printf("Area of the triangle = %.2lf\n", area);
  17.    
  18.    return 0;
  19. }
  20.  
  21. double area_of_triangle(double a, double b, double c)
  22. {
  23.    double s, area;
  24.    
  25.    s = (a+b+c)/2;
  26.    
  27.    area = sqrt(s*(s-a)*(s-b)*(s-c));
  28.    
  29.    return area;
  30. }