C++ Program to Find Area of Triangle
area = 0.5 * base * height and write a program that takes base and height as input and prints the area.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { double base, height, area; cout << "Enter base of the triangle: "; cin >> base; cout << "Enter height of the triangle: "; cin >> height; area = 0.5 * base * height; cout << "Area of the triangle is " << area << endl; return 0; }
Dry Run
Let's trace the example where base = 4 and height = 3 through the code
Input base
User enters base = 4
Input height
User enters height = 3
Calculate area
area = 0.5 * 4 * 3 = 6
Output area
Prints 'Area of the triangle is 6'
| Step | Base | Height | Area |
|---|---|---|---|
| Input | 4 | - | - |
| Input | 4 | 3 | - |
| Calculate | 4 | 3 | 6 |
| Output | 4 | 3 | 6 |
Why This Works
Step 1: Input base and height
The program asks the user to enter the base and height values using cin.
Step 2: Calculate area
It calculates the area using the formula 0.5 * base * height, which is the standard formula for triangle area.
Step 3: Display result
Finally, it prints the calculated area using cout so the user can see the result.
Alternative Approaches
#include <iostream> #include <cmath> using namespace std; int main() { double a, b, c, s, area; cout << "Enter sides a, b, and c: "; cin >> a >> b >> c; s = (a + b + c) / 2; area = sqrt(s * (s - a) * (s - b) * (s - c)); cout << "Area of the triangle is " << area << endl; return 0; }
#include <iostream> using namespace std; int main() { int base, height; cout << "Enter base and height: "; cin >> base >> height; double area = 0.5 * base * height; cout << "Area of the triangle is " << area << endl; return 0; }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of arithmetic operations and input/output steps, so it runs in constant time.
Space Complexity
It uses a few variables to store inputs and the result, so space usage is constant.
Which Approach is Fastest?
Both base-height formula and Heron's formula run in constant time, but base-height is simpler and faster since it uses fewer operations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Base and Height Formula | O(1) | O(1) | When base and height are known |
| Heron's Formula | O(1) | O(1) | When all three sides are known |