Java Program to Calculate Area of Triangle
area = 0.5 * base * height. For example: double area = 0.5 * base * height;.Examples
How to Think About It
Algorithm
Code
import java.util.Scanner; public class TriangleArea { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter base of the triangle: "); double base = scanner.nextDouble(); System.out.print("Enter height of the triangle: "); double height = scanner.nextDouble(); double area = 0.5 * base * height; System.out.println("Area of triangle is " + area); scanner.close(); } }
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.0
Print result
Output: Area of triangle is 6.0
| Step | Variable | Value |
|---|---|---|
| 1 | base | 4 |
| 2 | height | 3 |
| 3 | area | 6.0 |
Why This Works
Step 1: Read inputs
The program reads the base and height values from the user using Scanner.
Step 2: Calculate area
It calculates the area using the formula 0.5 * base * height, which gives the correct area of a triangle.
Step 3: Display output
Finally, it prints the calculated area to the screen for the user to see.
Alternative Approaches
import java.util.Scanner; public class TriangleAreaHeron { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter side a: "); double a = scanner.nextDouble(); System.out.print("Enter side b: "); double b = scanner.nextDouble(); System.out.print("Enter side c: "); double c = scanner.nextDouble(); double s = (a + b + c) / 2; double area = Math.sqrt(s * (s - a) * (s - b) * (s - c)); System.out.println("Area of triangle is " + area); scanner.close(); } }
public class TriangleAreaFixed { public static void main(String[] args) { double base = 5; double height = 8; double area = 0.5 * base * height; System.out.println("Area of triangle is " + area); } }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of operations (input reading, multiplication, division), 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 base-height formula is fastest and simplest; Heron's formula is slower due to square root calculation and more inputs.
| 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 |
| Fixed Values | O(1) | O(1) | Quick calculation without user input |