Thursday, 13 June 2013

A simple C++ program to calculate the area of a triangle using Heron's formula.

In this example, I assume that you know the Heron's formula and I only provide the code to implement it.
If you have a question, just post it as a comment and I will get back at you.

#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main()
{
//Declaring the variables
double a,b,c,sum1,sum2,sum3,p,area;

//Getting the values from user and setting conditions.
cout<<"Please enter the First side of the triangle:\n";
cout<<"a=";
cin>>a;
 if (a<=0)
     {
        cout<<"The length can neither be Negative nor 0!!!\nPlease start all over again.\n";
        system("pause");
        return 0;
     }
cout<<endl;
cout<<"Please enter the Second side of the triangle:\n";
cout<<"b=";
cin>>b;
 if (b<=0)
     {
        cout<<"The length can neither be Negative nor 0!!!\nPlease start all over again.\n";
        system("pause");
        return 0;
     }
cout<<endl;
cout<<"Please enter the Third side of the triangle:\n";
cout<<"c=";
cin>>c;
 if (a<=0)
     {
        cout<<"The length can neither be Negative nor 0!!!\nPlease start all over again.\n";
        system("pause");
        return 0;
     }
 cout<<endl;
 //Working out the area and setting other conditions.
sum1=a+b;
 if(sum1<=c)
     {
        cout<<"Invalid side specifications!!!\n(a+b>c...Please input correct side specifications.)";
        system("pause");
        return 0;
     }
sum2=a+c;
 if(sum2<=b)
     {
        cout<<"Invalid side specifications!!!\n(a+c>b...Please input correct side specifications.)";
        system("pause");
        return 0;
     }
sum3=b+c;
 if(sum3<=a)
     {
        cout<<"Invalid side specifications!!!\n(b+c>a...Please input correct side specifications.)";
        system("pause");
        return 0;
     }

p=(a+b+c)/2;
area= sqrt(p*(p-a)*(p-b)*(p-c));
cout<<"The area of the triangle is:\n"<<area;

_getch();
return 0;
}

No comments:

Post a Comment