RUN


Understanding the problem

We have to write a program that accepts three sides of a triangle from the user and prints its area. To calculate the area of a triangle from the three given sides, we use Heron’s Formula:

Area = s*(s-a)*(s-b)*(s-c),

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

Algorithm

  1. Take input of the three sides of the triangle from the user and store them in the variables a, b and c.
  2. Now declare a variable of float type and calculate and store the half perimeter in it. (don’t forget to use explicit typecasting since ‘s’ is of float type and a, b, c are int)
  3. Declare a variable area of float type and calculate and store area of the triangle in it using s and the given formula.
  4. Print area.

Code:

#include <iostream>
#include<cmath> //to use sqrt function
using namespace std;

int main()
{
  int a,b,c; //taking input of the three sides from the user

    cout << "Enter the three sides of the triangle\n";

    cin>>a>>b>>c;

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

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

    cout<<"Area="<<area; //printing the area

    return 0;

}

Output:

Enter the three sides of the triangle:
5 10 12
Area = 24.5446

Report Error/ Suggestion

Related Posts:

[yuzo_views]



Interview Questions



CopyRight © 2020

CopyRight © 2020