Monday, October 24, 2016

Java Program to calculate area of Traingle

In this session we will learn how to find the area of triangle.This is one of the basic java program and frequently asked java program in interview round too.

To find the Area of  Triangle,we have to multiply the base by the height and divide by 2. Here the reason why we need to divide by 2 the solution is:



The division by 2 comes from the fact that the parallelogram can be divided into 2 triangles.

Example:
                        The fallowing diagrams shows the area of each triangle is equal to one-half the area of the parallelogram.
Since The are of the parallelogram is A=b.h, The are of the triangle must be one-half  of the parallelogram. Therefore, the formula is 

                                             A=1/2*b*h (or) A=b*h/2

Note:  Here b means base and h means height. The base and height of a triangle must be perpendicular to each other.

Based upon this formula  i am going to write a Java Program to find the area of triangle.

Example 1:

class AreaOfTriangle
{
public static void main(String args[])
{
int b,h;
float a;
b=45;
h=34;
a=(float)1/2*b*h;
System.out.println("Area of triangle is:"+a);
}
}


Output:

Area of triangle is: 765.0

Explanation:

In the above example i have taken  name of the class is AreaOfTrianlge  and member variables are declared as  integer data types(base,height) and one more data type is float to store final result that means after calculating area of triangle and print the result named as a,then i used formula to find area of triangle.In the formula i used as float before 1/2 for typecasting. I have declared two integer variables then result will come as integer value. If you use float before 1/2 it converts into 1.0/2.0. 

 
Example 2:


class AreaOfTriangle
{
public static void main(String args[])
{
int b,h;
float a;
 b=Integer.parseInt(args[0]);
h=Integer.parseInt(args[1]);
a=(float)1/2*b*h;
System.out.println("Area of triangle is"+a);
}
}


OUTPUT: 

E:\>javac AreaOfTriangle.java
E:\>java AreaOfTriangle 23 13
Area of triangle is149.5


Explanation:

In the Example 2 program, enter the input from the user that means base and height values dynamically at run time. To get input from command prompt  i used Integer class and parseInt method(to convert String to int ).

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...