Home »
C++ Programs
C++ program to find area of a triangle by heron's formula using class
Learn, how can we find area of a triangle by heron's formula using the class and object approach?
Submitted by Shubh Pachori, on September 05, 2022
Problem statement
Find area of a triangle by heron's formula using the class and object approach.
Example:
Input:
Enter 1st Side: 12
Enter 2nd Side: 13
Enter 3rd Side: 11
Output:
Area : 61.4817
C++ code to find area of a triangle by heron's formula using the class and object approach
#include <math.h>
#include <iostream>
using namespace std;
// create a class
class AreaTriangle {
// private data members
private:
float side_1, side_2, side_3;
// public member functions
public:
// getSides() function to get the
// length of sides
void getSides() {
cout << "Enter 1st Side: ";
cin >> side_1;
cout << "Enter 2nd Side: ";
cin >> side_2;
cout << "Enter 3rd Side: ";
cin >> side_3;
}
// areaHerons() function to find area
// of triangle by heron's formula
double areaHerons() {
// initializing float type variables
// to perform operations
float area, temp;
// calculating average of all sides
temp = (side_1 + side_2 + side_3) / 2;
// calculating area of the triangle
area = sqrt(temp * (temp - side_1) * (temp - side_2) * (temp - side_3));
// returning area
return area;
}
};
int main() {
// create a object
AreaTriangle A;
// float type variable to store area
float area;
// getSides() function is called by the
// object to get length of sides
A.getSides();
// areaHerons() function to
// find area of triangle
area = A.areaHerons();
cout << "Area : " << area;
return 0;
}
Output
Enter 1st Side:10.5
Enter 2nd Side:11.1
Enter 3rd Side:12.2
Area : 54.2995
Explanation
In the above code, we have created a class AreaTriangle, three float type data members side_1, side_2 and side_3 to store the length of the sides, and public member functions getSides() and areaHerons() to store the length of sides and to calculate the area of the triangle.
In the main() function, we are creating an object A of class AreaTriangle, reading the inputted length of sides by the user using getSides() function, and finally calling the areaHerons() member function to calculate the area of the triangle. The areaHerons() function contains the logic to calculate the area and printing the result.
C++ Class and Object Programs (Set 2) »