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 <stdio.h> int main() { float base, height, area; printf("Enter base of the triangle: "); scanf("%f", &base); printf("Enter height of the triangle: "); scanf("%f", &height); area = 0.5f * base * height; printf("Area of triangle = %.2f\n", area); return 0; }
Dry Run
Let's trace the example where base = 4 and height = 5 through the code
Input base
User enters base = 4
Input height
User enters height = 5
Calculate area
area = 0.5 * 4 * 5 = 10
Print area
Output: Area of triangle = 10.00
| Step | Variable | Value |
|---|---|---|
| 1 | base | 4 |
| 2 | height | 5 |
| 3 | area | 10 |
Why This Works
Step 1: Input base and height
The program asks the user to enter the base and height values using scanf.
Step 2: Calculate area
It calculates the area by multiplying base and height, then multiplying by 0.5 using the formula area = 0.5 * base * height.
Step 3: Display result
Finally, it prints the area with two decimal places using printf.
Alternative Approaches
#include <stdio.h> #include <math.h> int main() { float a, b, c, s, area; printf("Enter sides a, b and c: "); scanf("%f %f %f", &a, &b, &c); s = (a + b + c) / 2; area = sqrt(s * (s - a) * (s - b) * (s - c)); printf("Area of triangle = %.2f\n", area); return 0; }
#include <stdio.h> int main() { int base, height; float area; printf("Enter base and height: "); scanf("%d %d", &base, &height); area = 0.5f * base * height; printf("Area of triangle = %.2f\n", area); return 0; }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of operations regardless of input size, so time complexity is constant O(1).
Space Complexity
Only a few variables are used to store inputs and the result, so space complexity is constant O(1).
Which Approach is Fastest?
The direct formula method is fastest and simplest. Heron's formula is more complex and slower due to extra calculations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Base and height formula | O(1) | O(1) | Simple cases with known height |
| Heron's formula | O(1) | O(1) | When only sides are known |
| Integer inputs with float output | O(1) | O(1) | When inputs are integers but precise area needed |