
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculating the Area of a Triangle Using Heron’s Formula in C++
Problem Description
We are given the three sides of a triangle, and we have to calculate the area of the triangle using Heron's formula. In this article, we are going to discuss how we can calculate the area of a triangle using Heron's Formula in C++.
Heron's Formula
The formula for calculating the semi-perimeter of the triangle is:
s = (a + b + c) / 2
Then, apply Heron's formula to calculate the area of the triangle.
Heron's formula for calculating the area of the triangle is:
Area = ? s * (s - a) * (s - b) * (s - c)
Return the area of the triangle after calculating.
Examples
Here are the examples with input and output values:
Example 1
-
Input
a = 5
b = 12
c = 13 -
Output
30
Explanation
The three sides of the triangle are: a = 5, b = 12, and c = 13.
The Semi-perimeter of the triangle: s = (a + b + c) / 2 = (5 + 12 + 13) / 2 = 15.
The area of the triangle: Area = ?15 * (15 - 5) * (15 - 12) * (15 - 13)
?15 * 10 * 3 * 2 = ?900 = 30.
Example 2
-
Input
a = 7
b = 24
c = 25 -
Output
84
Explanation
The three sides of the triangle are: a = 7, b = 24, and c = 25.
The Semi-perimeter of the triangle: s = (a + b + c) / 2 = (7 + 24 + 25) / 2 = 28.
The area of the triangle: Area = ?28 * (28 - 7) * (28 - 24) * (28 - 25)
?28 * 21 * 4 * 3 = ?7056 = 84.
Example 3
-
Input
a = 6
b = 8
c = 10
-
Output
24
Explanation
The three sides of the triangle are: a = 6, b = 8, and c = 10.
The Semi-perimeter of the triangle: s = (a + b + c) / 2 = (6 + 8 + 10) / 2 = 12.
The area of the triangle: Area = ?12 * (12 - 6) * (12 - 8) * (12 - 10)
?12 * 6 * 4 * 2 = ?576 = 24.
Calculating Area of a Triangle Using Heron's Formula
To calculate the area of a triangle, we use the direct formula to calculate the area of a triangle. We use Heron's formula to calculate the area of the triangle. We first calculate the semi-perimeter of the triangle.
Implementation Code
#include<bits/stdc++.h> using namespace std; double areaOfTriangle(double a, double b, double c) { // Step 1: Calculate the semi-perimeter double s = (a + b + c) / 2; // Step 2: Apply Heron's Formula double area = sqrt(s * (s - a) * (s - b) * (s - c)); return area; } int main() { double a = 5; double b = 12; double c = 13; // Calculate the area double area = areaOfTriangle(a, b, c); // Output the result cout << "The area of the triangle is: " << area << endl; return 0; }
Output
The area of the triangle is: 30
Time Complexity: O(1)
Space Complexity: O(1)