Write a program to find the area of a triangle , follow these steps: Accept the
ID: 3606018 • Letter: W
Question
Write a program to find the area of a triangle , follow these steps:
Accept the sides of a triangle in the main.
Build a function to accept the sides of the triangle (check if the sides form a triangle if yes returns the area otherwise returns zero.
Call the function from the main then print the area of the triangle in the main if the sides form a triangle, if not print “sides don’t form a triangle”.
Let the program find the area for three triangles.
Hint: use this formula to find the triangle area:
Hint: use this formula to find the triangle area: Area-Vs(s-a) (s-b) (s-c)Explanation / Answer
Ans.) In Java,
Program :
import java.util.*;
import java.lang.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
//Taking three sides of the triangle as input using Scanner class.
System.out.println("Enter the 3 sides of a triangle?");
double x=sc.nextDouble();
double y=sc.nextDouble();
double z=sc.nextDouble();
//Calling the printArea() method to calculate the area of the triangle.
double area=printArea(x,y,z);
if(area!=0){
System.out.println("The area of the triangle is : "+area+" square units.");
}
else{
System.out.println("Sides don’t form a triangle!");
}
}
//printArea() method to calculate the area of triangle.
static double printArea(double x, double y, double z){
double area=0;
double s=(x+y+z)/2;
if(s!=0 && x>0 && y>0 && z>0){
double k=(s*(s-x)*(s-y)*(s-z));
area=Math.sqrt(k);
return area;
}
else{
//If s is 0, or any of the sides is 0, then it is not a triangle, hence return 0.
return 0;
}
}
}
Output1 :
Enter the 3 sides of a triangle?
1
2
3
Sides don?t form a triangle!
Output2:
Enter the 3 sides of a triangle?
3
4
3
The area of the triangle is : 4.47213595499958 square units.
Revert back via comment section, if you have any doubts or you want the program in any other programming language.
*No programming language was mentioned in the question, hence providing the answer in Java.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.