C# Program to Find Area of Triangle with Example
area = 0.5 * base * height and printing the result, for example: double area = 0.5 * baseLength * height; Console.WriteLine(area);.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { Console.Write("Enter base of triangle: "); double baseLength = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter height of triangle: "); double height = Convert.ToDouble(Console.ReadLine()); double area = 0.5 * baseLength * height; Console.WriteLine("Area of triangle is " + area); } }
Dry Run
Let's trace the example where base = 4 and height = 3 through the code
Input base
User enters 4, so baseLength = 4
Input height
User enters 3, so height = 3
Calculate area
area = 0.5 * 4 * 3 = 6
Print result
Output: Area of triangle is 6
| Step | Variable | Value |
|---|---|---|
| 1 | baseLength | 4 |
| 2 | height | 3 |
| 3 | area | 6 |
Why This Works
Step 1: Getting inputs
We ask the user to enter the base and height, which are needed to calculate the area.
Step 2: Calculating area
We use the formula area = 0.5 * base * height because the area of a triangle is half the product of its base and height.
Step 3: Displaying output
We print the calculated area so the user can see the result.
Alternative Approaches
using System; class Program { static void Main() { Console.Write("Enter side a: "); double a = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter side b: "); double b = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter side c: "); double c = Convert.ToDouble(Console.ReadLine()); double s = (a + b + c) / 2; double area = Math.Sqrt(s * (s - a) * (s - b) * (s - c)); Console.WriteLine("Area of triangle is " + area); } }
using System; class Program { static double TriangleArea(double b, double h) { return 0.5 * b * h; } static void Main() { Console.Write("Enter base: "); double baseLength = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter height: "); double height = Convert.ToDouble(Console.ReadLine()); double area = TriangleArea(baseLength, height); Console.WriteLine("Area of triangle is " + area); } }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of operations (input, multiplication, output), so it runs in constant time.
Space Complexity
Only a few variables are used to store inputs and the result, so space usage is constant.
Which Approach is Fastest?
The direct formula method is fastest and simplest; Heron's formula is slower due to square root calculation but useful when height is unknown.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct formula (0.5 * base * height) | O(1) | O(1) | Known base and height |
| Heron's formula | O(1) | O(1) | Known all three sides, height unknown |
| Function-based calculation | O(1) | O(1) | Code reuse and clarity |