Write a program to find the area of the triangle.
Example 1:
Input: base=12,height=7
Output: 42
Example 2:
Input: base=13,height=5;
Output:32.5
Approach 1: Given base and height.
Area is 1/2*base*height
Java
public class AreaofTriangle {public static void main(String[] args) {double base = 12;double height = 7;double area = areaTriangle(base, height);System.out.println("Area of triangle is " + area);}private static double areaTriangle(double base, double height) {return (base * height) / 2;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find area of//triangledouble areaTriangle(double base,double height){double area=(base*height)/2;return area;}int main(){double base=12;double height=7;double area=areaTriangle(base,height);cout<<"Area of triangle is ";cout<<area<<"\n";return 0;}
Example 1:
Input: side1=5,side2=12,side3=13
Output: 30.0
Approach 2:Given all sides length. Using heron's formula.
Java
public class AreaofTriangle1 {public static void main(String[] args) {double side1 = 3;double side2 = 4;double side3 = 5;double area = areaTriangle(side1, side2, side3);System.out.println("Area of triangle is " + area);}private static double areaTriangle(double side1, double side2, double side3) {double s = (side1 + side2 + side3) / 2;double area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));return area;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find area of//triangledouble areaTriangle(double side1,double side2,double side3){double s=(side1+side2+side3)/2;double area=sqrt(s*(s-side1)*(s-side2)*(s-side3));return area;}int main(){double side1=3;double side2=4;double side3=5;double area=areaTriangle(side1,side2,side3);cout<<"Area of triangle is ";cout<<area<<"\n";return 0;}
No comments:
Post a Comment