Calculate the Area of a Triangle Using a Function in C++

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.

Understanding how to create and use functions is essential in programming as it improves code organization and reusability. This particular problem also involves applying the basic geometry formula for the area of a triangle: (base × height) / 2.

By completing this exercise, you will gain experience with user input, function definition and usage, and mathematical operations in C++.

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

 Copy 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

Share this C++ Exercise


More C++ Programming Exercises of Functions in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.