Sunday, July 13, 2008

Area of a triangle, given three sides, C learn by Example, Tutorial

/* Write a C program to find the area of a triangle, given three sides*/

#include stdio.h
#include conio.h
#include math.h

void main()
{
int s, a, b, c, area;
clrscr();

printf("Enter the values of a,b and c\n");
scanf ("%d %d %d", &a, &b, &c);

/* compute s*/

s = (a + b + c) / 2;

area = sqrt ( s * (s-a) * (s-b) * (s-c));

printf ("Area of a triangale = %d\n", area);
}

/*-----------------------------
Output

Enter the values of a,b and c
3
4
5
Area of a triangale = 6
------------------------------*/

This program uses the formula area = square root of (s*(s-a)*(s-b*(s-c)).

Indorer to use execute this we need to use the command sqrt() (square root function) which is predefined in math.h header file. So we are declaring that file in the preprcessor statements. Rest else is straight forward

2 comments:

Unknown said...

what will happen if either value of a,b or c is greater than s,then sqrt(-) will not give us the resultant output.I think the formula is not so helpful as per we are using this program.
Please reply

Unknown said...

If we take a=2,b=4,c=8 then s=(a+b+c)/2 gives s=7.
Now s-a=5,s-b=3,s-c=-1 then s*(s-a)*(s-b)*(s-c) will give result as -105.
Now sqrt(-105) will not be executed while running the program.
How it is so,that means the formula is not applicable if s is less than either one side of a or either three sides of a.
Please reply soon