Area of Triangle Program in java

0

In this article we are going to Write a program to calculate area of triangle.

Lets understand what is Triangle, A triangle is a polygon with three edges and three vertices. It is one of the basic shapes in geometry. When the height and base of the triangle are given, then the area of the triangle is half the product of its base and height.



To find the area of triangle we can use below formula:

Area of triangle: Area = (height×base)/2

Example 1: Area of Triangle in Java using Scanner

The Scanner class is used to get user input, and it is found in the java.util package. Here we using Scanner class to accept user input for base and height.


import java.util.Scanner;

public class Main
{
   public static void main(String[] args) {
    
     Scanner sc = new Scanner(System.in);
    
     //Accept user input for Base of Triangle
     System.out.println("Enter the Base of Triangle: ");
     float base = sc.nextFloat();
    
     //Accept user input for Height of Triangle
     System.out.println("Enter the Height of Triangle: ");
     float height = sc.nextFloat();
    
     //calculate area
     float areaOfTriangle = (base * height)/2;
     System.out.println("Area of Triangle: "+areaOfTriangle);
    
   }
}

Output:


Enter the Base of Triangle: 
5
Enter the Height of Triangle: 
10
Area of Triangle: 25.0


Example 2: Java Program to Find Area of Triangle using Constructor

In this program we use constructor to find the area of rectangle. Constructor is use to initialize the value for object attributes.  constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory


import java.util.Scanner;

class AreaOfRectangle {
   long area;

   //Constructor
   AreaOfRectangle(long b, long h) {
     area = (* h) / 2;
   }
}

class Main {

   public static void main(String args[]) {

     Scanner sc = new Scanner(System.in);
     //Accept the user input for width
     System.out.println("Enter the width of the Triangle:");
     long breadth = sc.nextLong();

     //Accept the user input for height
     System.out.println("Enter the height of the Triangle:");
     long height = sc.nextLong();
    
     //close scanner after use
     sc.close();

     //created AreaOfRectangle object
     AreaOfRectangle obj = new AreaOfRectangle(breadth, height);
     System.out.println("Area of Triangle is: " + obj.area);
   }
}


Output:


Enter the Base of Triangle: 
5
Enter the Height of Triangle: 
8
Area of Triangle: 20



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !