Calculate the Area of a Triangle
This C++ exercise focuses on using functions to encapsulate reusable logic for mathematical calculations. The task is to write a function that calculates the area of a triangle given its base and height using the geometric formula: $Area = \frac{base \times height}{2}$.
Implementation Details
1. Float Precision
Using float or double allows the program to handle decimal dimensions and provide accurate area results.
2. Parameter Passing
The function accepts base and height as arguments, keeping the calculation independent of user input logic.
3. Encapsulation
By moving the formula to a function, the code becomes more organized and easier to reuse in larger geometry projects.
Reusability Note:
Once defined, calculateTriangleArea() can be called multiple times with different values without rewriting the mathematical logic.
Objective
- 1. Define a function that takes two
floatparameters. - 2. Implement the formula
(base * height) / 2. - 3. Return the calculated area as a
float. - 4. Capture user input in
main()and display the final result.
Example C++ Exercise
#include <iostream>
using namespace std;
// Function to calculate the area of a triangle
float calculateTriangleArea(float base, float height) {
// Formula: (base * height) / 2
return (base * height) / 2.0f;
}
int main() {
float base, height;
cout << "Enter the base of the triangle: ";
cin >> base;
cout << "Enter the height of the triangle: ";
cin >> height;
// Call function and store result
float area = calculateTriangleArea(base, height);
cout << "The area of the triangle is: " << area << endl;
return 0;
}
Example Output:
Enter the height of the triangle: 5
The area of the triangle is: 25