Hello coders, I hope you are well and getting benefits from Tutorialsfield’s tutorials. In the previous tutorial, we have learned Java Program to calculate Area and Circumference of Circle. In today’s tutorial, we will learn Java Program to Calculate Area of Triangle.
Calculating the area of the triangle in Java is very easy and can be done in a few simple steps. Let’s see them.
Before writing the program, we need to know the formula for calculating the area of a triangle. The formula is here –
Area of triangle = 1/2 * base * height
Now let’s start writing code. Here is the complete Java Program to Calculate Area of Triangle, and the explanations are given after the program.
Java Program to Calculate Area of Triangle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.*; public class Triangle { public static void main(String[] args) { double width, height, area; Scanner in = new Scanner(System.in); // Asking the user to enter the width of the triangle System.out.println(" Enter the width of triangle :"); width = in.nextDouble(); // Asking the user to enter the height of the triangle System.out.println(" Enter the height of triangle :"); height = in.nextDouble(); area = (width*height)/2; // Calculating area of triangle System.out.println(" Area of triangle : " + area +" square units"); } } |
What we did ?
- First of all we have imported the util package.
- Then created a class and named it Triangle.
- After that started main() method of the program.
- Then inside main() method declared three variables width, height, and area which we will use in this program.
- Then created object of the Scanner class.
- Now asked the user to enter the width of the triangle. Then read the value of width entered by the user.
- Now asked the user to enter the height of the triangle. Then read the value of height entered by the user.
- Then calculated area of the triangle using the formula area = (width*height)/2.
- Then finally printed the value of area of triangle on the screen.
Output:
1 2 3 4 5 |
Enter the width of triangle : 3 Enter the height of triangle : 2 Area of triangle : 3.0 square units |
So guys, we have learned Java Program to Calculate Area of Triangle. In the next tutorial we will learn Java Program to calculate Area of Triangle using heron’s formula.
Related Tutorials…
- Java Program to Calculate Area and Circumference of Circle
- Java Program to calculate Area and Perimeter of Right Triangle
- Java Program to calculate Area and Perimeter of Rectangle
- Java Program to calculate Area and Perimeter of Square
- Java Prorgram to calculate Area and Perimeter of Parallelogram
- Java Program to calculate Area of Trapezium
- Java Program to calculate Area and Volume of Cube
- Java Program to calculate Area and Volume of Cuboid
- Java Program to calculate Total Surface Area and Curved Surface Area of cylinder
- Java Program to calculate Volume of Cone
- Java Program to calculate Surface Area and Volume of Sphere