Java Programming | Area of triangle

Join Programming and Development Chat Groups on Uphub.io

Introduction

This is a tutorial for area of triangle in java. The program calculates the area of triangle and prints it. The program is extendable. Go enjoy the program. Lets begin…….

Program for area of triangle in java


//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class TriangleArea {
//void main
public static void main (String[] args)
{
//declare float
float area,a,b;
//print message
System.out.println("Enter base and height of triangle:");
//Take input
Scanner input = new Scanner(System.in);
a = input.nextInt();
b = input.nextInt();
//calculate
area = 0.5f*a*b;
//print the area
System.out.println("Area = "+area);
}
}

Output

Enter base and height of triangle:
2
4
Area = 4.0

How it works

  1. The program prints the message to enter numbers.
  2. The user enters base and height of triangle.
  3. Area is calculated.
  4. The area is printed.

Extending it

The program can be extended by taking more different shapes and calculating their area.

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter base and height.
  5. Declare input as Scanner.
  6. Take the base and height and save it in variable.
  7. Calculate area and save it in other variable.
  8. Add system.out.println() function to print the area.

At the end.

You learnt creating the Java program for Area of Triangle. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Sharing options: