Computer Science, asked by nirav05, 4 months ago

Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5 units by creating a class named 'Triangle' with constructor having the three sides as its parameters.

Answers

Answered by irfanshaikhh871
7

Answer:

import static java.lang.Math.sqrt;

class Triangle

{  

int a,b,c;

public double getArea()

{

double p=(a+b+c)/2.0;

return Math.sqrt(p*(p-a)*(p-b)*(p-c));

}

public double getPerimeter()

{

 return (a+b+c)/2.0;

}

}

class Perimeter

{

public static void main(String args[])

{

 Triangle t=new Triangle();

 t.a=3;

 t.b=4;

 t.c=5;

 System.out.println("Area of Triangle is: " +t.getArea());

 System.out.println("Perimeter of Triangle is: " +t.getPerimeter());

}

}

OUTPUT:

6.0

6.0

Explanation:

1. Create a class name Triangle

2. Ask is for 3 sides of triangle. Declare a,b,c which would take values as   3,4,5.

3. Once sides are created, we now have to calculate the area of triangle   and perimeter of triangle. Formula for area of triangle with 3 sides is:

(p*(p-a)*(p-b)*(p-c)) where p=(a+b+c)/2

area of perimeter is: (a+b+c)/2

4. Now to calculate area of triangle declare a double variable p which calculates the value (a+b+c)/2.0 (since we have taken double). Now we got the value of p.

5. Now import {import static java.lang.Math.sqrt;} package for calculating area of triangle.  use formula

take return type and formula Math.sqrt(p*(p-a)*(p-b)*(p-c))

which makes: return Math.sqrt(p*(p-a)*(p-b)*(p-c)); (Here we get area of tri)

6. Now we have to calculate perimeter of triangle. Declare a method with getPerimeter() and return value: return a+b+c)/2.0

7. Create main class and create object for Triangle class

                Triangle t=new Triangle();

8. Assign values a,b,c using reference variable 't' and printout the result.

Similar questions