Sunday, September 24, 2023

How to calculate area of Triangle in Java - Example Solution

Calculate the area of Triangle in Java
Write a Java program to calculate Area of Triangle, accept input from User, and display output in Console is one of the frequently asked homework questions. This is not a tough programming exercise but a good exercise for beginners and anyone who has started working in Java. For calculating the area of a triangle using the formula 1/2(base*height), you need to use arithmetic operators. By doing this kind of exercise you will understand how arithmetic operators work in Java, subtle details which affect calculation like precedence and associativity of the operator, etc.


Fortunately this question is not very popular on Java interview like other exercises we have seen e.g. Java program to print Fibonacci series and Java program to check for palindrome. Nevertheless, it's good Java homework.

Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join these online Data structures and Algorithms courses to improve their knowledge and algorithms skills. 



How to calculate the area of Triangle in Java

Java program to calculate area of triangle in Java with ExampleIn this section, we will see a complete code example of How to calculate the Area of Triangle in Java. We are going to use classic formula 1/2(base*height), where base and height will be accepted as user input using java.util.Scanner class. The arithmetic operator used in this exercise is multiplication and division i.e * and /.



/**
 *
 * Java program to calculate area of Triangle .
 * Formula for calculating area of Triangle is 1/2(base*height)
 *
 * @author Javin Paul
 */

public class AreaOfTriangle {

 
   
public static void main(String args[]) {
     
        Scanner scanner =
new Scanner(System.in);
     
        System.
out.println("Please enter base width of Triangle ");
       
float base = scanner.nextFloat();
     
        System.
out.println("Please enter height of Triangle ");
       
float height = scanner.nextFloat();
     
       
//calculating area of Triangle in Java
       
float area = area(base, height);
     
        System.
out.println("Area of Triangle calculated by Java program is : " + area);
   
   
}
 
   
public static float area(float base, float height){
       
return (base* height)/2;
   
}
}

Output
Please enter base width of Triangle
20
Please enter height of Triangle
30
Area of Traingle calculated by Java program is :
300.0

That's the whole Java program to calculate the area of a triangle and Now let me introduce with one of the most common mistake Java programmer makes while writing this code. If you look closely to area() method you will find that we have wrapped code into a small bracket i.e. (base* height)/2

We have done that to increase precedence, anything which is inside the bracket will be executed first. Just change the code, like you write in notebook e.g. 1/2*base*height and suddenly your calculate area for triangle become zero, as shown below :


public static float area(float base, float height){
   return 1/2*base*height;
}

Please enter base width of Triangle
10
Please enter height of Triangle
40
Area of Traingle calculated by Java program is : 0.0


For a beginner in Java,  this is not an easy bug to find or spot on. In order to find the bug, you must know-how Java evaluates an arithmetic expression. Here two arithmetic operators * and / are used which are right-associative i.e. evaluated from right to left and of the same precedence.

the first expression which is evaluated by Java is 1/2 which is a division of two integers and the result of this would be an integer i.e. zero and not 0.5, which is making the whole area zero. 

This is happening because both operands of division operator(/) are integer, if any of them is float or double then the result would be a floating-point number. by combining (base*height) in bracket we ensure that it is executed first and produce a floating-point number which can be divided by two. 

This kind of simple Java mistake can only be avoided by learning and writing such kind of program. That's why programs like How to calculate square root in Java should be on the list of Java learners.

That's all on How to calculate the Area of the Triangle in Java. We have seen complete code and also analyzed possible but and How arithmetic expression is evaluate in Java especially multiplication and division operators.


Other Java programming and homework exercise

And lastly one question for you? Which one is your favorite Java coding exercise? Palindrome, Prime number, Fibonacci, Factorial or this one? 

5 comments:

  1. Awesome code.... good thinking..... Now I realise why area always came 0.0..... but sir,
    I then tried (double)(1/2)*base*height; but still it is coming 0.0.... can you tell me why is it coming like that?

    ReplyDelete
    Replies
    1. When (1/2) is been operated,it's resulting 0.5 and ....the whole part of it ie 0 is been considered by the compiler ,that's why it's returning 0 and 0.0 is because of 'double'

      Delete
  2. how do you calculate area of triangle if only co-ordinates of vertices are given and no base or height is provided?

    ReplyDelete
  3. You can use following formula to calculate area of triangle with co-ordinates of all three vertices given

    area = (x1(y2 - y3) + x2(y3 - y1) + x3(y1 - y2))/2

    ReplyDelete
  4. import java.util.Scanner;

    /**
    * Calculates area of triangle in Java given its base and vertical height.
    * @author jj
    */
    public class AreaOfTriangle1 {

    public static void main(String[] args) {

    Scanner sn = new Scanner(System.in);
    System.out.println("Enter base of triangle:");
    double base = sn.nextDouble();

    System.out.println("Enter vertical height of triangle:");
    double verticalHeight = sn.nextDouble();

    AreaOfTriangle1 at = new AreaOfTriangle1();
    double area = at.calculateArea(base,verticalHeight);

    System.out.println("Area = "+area);

    }

    /**
    * Calculates area of a triangle using base and vertical height
    * @param base
    * @param verticalHeight
    * @return
    */
    private double calculateArea(double base, double verticalHeight) {
    return base*verticalHeight/2;
    }
    }

    ReplyDelete