C program to find area of a triangle

Area of a triangle can simply be evaluated using following formula.

Area = sqrt(s*(s-a)*(s-b)*(s-c))
where a, b and c are lengths of sides of
triangle and s = (a+b+c)/2

C

#include <stdio.h>
#include <stdlib.h>

float findArea(int a, int b, int c)
{
     // Length of sides must be positive and sum of any two sides
     // must be smaller than third side.
    if (a < 0 || b < 0 || c <0 || (a+b <= c) ||
        a+c <=b || b+c <=a)
    {
        printf("Not a valid trianglen");
        exit(0);
    }
    int s = (a+b+c)/2;
    return sqrt(s*(s-a)*(s-b)*(s-c));
}

int main()
{
    int a  = 3;
    int b = 4;
    int c = 5;

    printf("Area is %f", findArea(a, b, c));
    return 0;
}

Java

// Java program to print
// Floyd's triangle
    
class Test
{
    static float findArea(int a, int b, int c)
    {
         // Length of sides must be positive and sum of any two sides
         // must be smaller than third side.
        if (a < 0 || b < 0 || c <0 || (a+b <= c) ||
            a+c <=b || b+c <=a)
        {
            System.out.println("Not a valid triangle");
            System.exit(0);
        }
        int s = (a+b+c)/2;
        return (float)Math.sqrt(s*(s-a)*(s-b)*(s-c));
    }
         
    // Driver method
    public static void main(String[] args) 
    {
        int a = 3;
        int b = 4;
        int c = 5;
     
        System.out.println("Area is " + findArea(a, b, c));
    }
}


Output:
Area is 6.000000

Finding area using coordinates:
If we are given coordinates of three corners, we can apply below Shoelace formula for area.

Area
formula
 = | 1/2 [ (x1y2 + x2y3 + ... + xn-1yn + xny1) -
           (x2y1 + x3y2 + ... + xnyn-1 + x1yn) ] |

// C++ program to evaluate area of a polygon using
// shoelace formula
#include <bits/stdc++.h>
using namespace std;
 
// (X[i], Y[i]) are coordinates of i'th point.
double polygonArea(double X[], double Y[], int n)
{
    // Initialize area
    double area = 0.0;
 
    // Calculate value of shoelace formula
    int j = n - 1;
    for (int i = 0; i < n; i++)
    {
        area += (X[j] + X[i]) * (Y[j] - Y[i]);
        j = i;  // j is previous vertex to i
    }
 
    // Return absolute value
    return abs(area / 2.0);
}
 
// Driver program to test above function
int main()
{
    double X[] = {0, 2, 4};
    double Y[] = {1, 3, 7};
 
    int n = sizeof(X)/sizeof(X[0]);
 
    cout << polygonArea(X, Y, n);
}

Output :

2

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.