Group
Functions in C++
Objective
1. Define a function that takes two float parameters: base and height.
2. Use the formula area = (base × height) / 2 to calculate the area.
3. Return the result from the function.
4. In the main function, prompt the user to enter the base and height of the triangle.
5. Call the function and display the calculated area.
Create a function that calculates the area of a triangle.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
// Function to calculate the area of a triangle
float calculateTriangleArea(float base, float height) {
// Use the formula: (base × height) / 2
return (base * height) / 2;
}
// Main function - entry point of the program
int main() {
float base, height; // Variables to store the base and height
// Ask the user to enter the base of the triangle
cout << "Enter the base of the triangle: ";
cin >> base; // Read the base input
// Ask the user to enter the height of the triangle
cout << "Enter the height of the triangle: ";
cin >> height; // Read the height input
// Call the function to calculate the area
float area = calculateTriangleArea(base, height);
// Display the result
cout << "The area of the triangle is: " << area << endl;
return 0; // End of the program
}
Output
Enter the base of the triangle: 10
Enter the height of the triangle: 5
The area of the triangle is: 25