Wednesday 13 November 2013

C++ Program to calculate area of a triangle!

Nothing much to explain! Here we assume the user has any one of these two information:

  1. He knows all three sides, but doesn't know which side is base or which one is height.
  2. He knows the base and the height.
In the first case we use Heron's Formula :




And in the second, we use the familiar method : 


Here is the code:
#include<iostream.h>
#include<conio.h>
#include<math.h>
int Heron(int a, int b, int c);
int Normal(int b, int h);
int main()
{
    int choice;
    float first, second, third, base, height;
    cout<<"Select your choice : "<<endl;
    cout<<"1. You have three sides of the triangle, but are not sure which one is base or which one is height"<<endl;
    cout<<"2. You have two sides, one base and one height"<<endl;
    cin>>choice;
    switch(choice)
    {
       case 1:
          cout << "Enter the sides : " << endl;
          cin >> first >> second >> third;
          cout<<"\nArea is "<<Heron(first, second, third);
          break;
       case 2:
          cout<<"Enter the base : ";
          cin>>base;
          cout<<"Enter the height : ";
          cin>>height;
          cout<<"\nArea is "<<Normal(base, height);
          break;
       default:
          cout<<"\nInvalid choice!\n";

    }
    return 0;
}

int Heron(int a, int b, int c)
{
    float s = ((a + b + c) / 2);
    float area = sqrt( s * (s - a) * (s - b) * (s - c));
    cout << "Area is " << area << " Sq. Units";
    return area;
}

int Normal(int b, int h)
{
    float area = .5 * b * h;
    cout<<"Area is " << area << " Sq. Units"; 
    return area;
}


For newer IDEs, visit this page.

The special thing about this program is that we use the math library by including the header "math.h". Notice how we used the sqrt() function for the square root of the expression. 

Outputs on both options are :



That is all for today, folks!

1 comment:

You might also like