Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Area Of Triangle
3.
Approach
4.
By Using Coordinates of the Vertices of the Triangle
4.1.
Algorithm
4.2.
Implementation
4.3.
Complexity
5.
By using the Base and Height of the Triangle
5.1.
Algorithm
5.2.
Implementation
5.3.
Complexity
6.
By Using Heron’s Formula
6.1.
Algorithm
6.2.
Implementation
6.3.
Complexity
7.
For an Equilateral Triangle
7.1.
Algorithm
7.2.
Implementation
7.3.
Complexity
8.
Frequently Asked Questions
8.1.
Why the complexities of all the above algorithms for finding the area of a triangle are O(1)?
8.2.
What is the most used program to find area of a triangle?
8.3.
Is it necessary to include a maths function to do the maths operation?
8.4.
What are %c and %s, and why are they used?
8.5.
Why are format specifiers used in programming languages?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Write a Program to Find the Area of a Triangle

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

This article will discuss various approaches to writing a program to find area of a triangle. We will discuss approaches based on the information given to us. We will find the area using the coordinates of vertices, its base and height, and heron’s formula. We will also write a program to find area of a triangle if all the sides are equal, i.e., for an equilateral triangle. 

So without any further ado, let’s get started!

program to find area of a triangle

Also see: C Static Function, And Tribonacci Series

Area Of Triangle

In a two-dimensional plane, the area of a triangle is the region enclosed by it. A triangle is a closed shape with three sides and three vertices. Thus, the area of a triangle is the total space filled by the triangle's three sides. 

area of triangle

The general formula for calculating a triangle's area is half the product of its base and height. It is applicable to all forms of triangles, including scalene, isosceles, and equilateral triangles.

types of triangle
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Approach

We can write a program to find area of a triangle by using the info provided to us. We can be provided with any of the below-mentioned info.

  • The coordinates of the vertices of the triangle.
  • The base and height of the triangle.
  • The value of each side of the triangle.
  • The triangle given is an equilateral triangle.

By Using Coordinates of the Vertices of the Triangle

We can write a program to find area of a triangle using coordinates of the vertices. We will have three coordinates of the vertices of the triangle.

We will take a straightforward approach. As we all know, the formula for calculating the area of a triangle with coordinates is as follows:

{ (Ax, Ay), (Bx, By), (Cx, Cy) } is

Area = 1/2 ∣(Ax(By−Cy) + Bx(Cy−Ay) + Cx(Ay−By)∣

Let us now write the program that will convert this logic into code.

Algorithm

  1. We will take the input or assign the values of the coordinates of the triangle.
     
  2. Further, we will calculate the area using the formula.
    Area = 1/2 ∣(Ax(By−Cy) + Bx(Cy−Ay) + Cx(Ay−By)∣
     
  3. Print the area of the triangle.

Implementation

After learning the algorithm to write the program, let’s see its implementation in various programming languages.

Following a C language code for the above algorithm.

C

#include <stdio.h>
#include <math.h>

int main(void) {
    float Ax,Ay,Bx,By,Cx,Cy;
    
    printf("Enter the value of the coordinates Ax, Ay, Bx, By, Cx, Cy of the triangle:");
    scanf("%f %f %f %f %f %f",&Ax, &Ay, &Bx, &By, &Cx, &Cy);    
    
    float area = ((float)1 / 2) * abs((int) (Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By)));
    printf("AREA OF TRIANGLE IS %f",area);
}


Output

output of c

Now let’s have a look at a C++ program to find area of a triangle using its coordinates.

C++

#include <bits/stdc++.h>
#include <math.h>

using namespace std;

int main() {

    float Ax=1,Ay=1,Bx=6,By=1,Cx=2,Cy=3;
    float area;
    
    area= ((float)1 / 2) * abs((int) (Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By)));
    cout<<"AREA OF TRIANGLE IS "<< area;
}


Output

output for cpp

The Java program for the above algorithm is as follows.

Java

class AreaOfTriangle { 
    static double area(int x1, int y1, int x2, int y2, int x3, int y3)  {   
        return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);  
    }
     
    public static void main(String[] args)  {   
        int Ax = 2, Ay = 2;   
        int Bx = 8, By = 3;   
        int Cx = 4, Cy = 6;
          
        double area = area(Ax, Ay, Bx, By, Cx, Cy);   
        System.out.println("Area of Triangle is " + area); 
    }
}


Output

output for java

Now, let’s see the algorithm’s implementation in Javascript language.

JavaScript

var Ax=1,Ay=1,Bx=6,By=1,Cx=2,Cy=3;

var area =  ((0.5) * ((Ax * (By - Cy)) + (Bx * (Cy - Ay)) + (Cx * (Ay - By))));
console.log(“Area of triangle is”, area);


Output

output for js

The Python implementation of the above algo is as follows.

Python

x=[2,8,4]
y=[2,3,6]

def get_area(x,y):
    area=0.5* ( (x[0]*(y[1]-y[2])) + (x[1]*(y[2]-y[0])) + (x[2]*(y[0]-y[1])) )
    return int(area)

coords=list(zip(x,y))
print("Area of points {},{},{} is {}".format(*coords,get_area(x,y)))


Output

output of python

Complexity

The time and space complexity of the above algorithm is as follows.

Time Complexity

The time complexity of the algorithm is O(1)

Space Complexity

The space complexity of the algorithm is O(1)

You can also read about dynamic array in c and Short int in C Programming

By using the Base and Height of the Triangle

The most basic formula to find the area of a triangle is by using its base and height. We are using this formula from the primary standard. We can also write a program to find the area of triangle by using this formula. 

The formula states that the area of a triangle is half of the base value of the triangle multiplied by its height.

Area = (base*height)/2

We can use this formula to frame an algorithm. 

Algorithm

  1. We are given the base and height values of the triangle.
     
  2. Now, we will calculate the area by putting it into the equation.
          Area = (base*height)/2  
     
  3. Print the area of the triangle.

Implementation

Let us look into the C implementation of the above algorithm.

C

#include<stdio.h>  
#include <math.h>

int main(){

    float base, height, area;  
    printf("Enter the base and the height of the triangle:");
    scanf("%f %f", &base, &height);
    
    area = (base*height) / 2 ;  
  
    printf("Area of Triangle is : %f",area);  
    return 0;  
}


Output

output for cpp

Now let’s have a look at a C++ program to find area of a triangle using its base and height.

C++

#include<bits/stdc++.h>  
using namespace std;

int main(){
    float base,height, area;  
    base= 5;  
    height= 8;  
    area = (base*height) / 2 ;  
  
    cout<<"Area of Triangle is "<< area << endl;  
    return 0;  
}


Output

output for cpp

The Java program for the above algo is as follows.

Java

class Area {
    static double area(double base, double height) {
        return (base * height) / 2;
    }

    public static void main(String[] args) {
        double base = 5, height = 8;

        System.out.println("Area of the triangle: " + area(base, height));
    }
}


Output

output for java

Now, let’s see algo’s implementation in JavaScript language.

JavaScript

let base = 5, height=8;

// Calculating the area
const area = (base * height) / 2;

console.log(
  `The area of the triangle is ${area}`
);


Output

output for js

The Python implementation of above algo is as follows.

Python

base = 5  
height = 8
area = (base*height)/2  
print("Area of Triangle is :");  
print(area);


Output

output of python

Complexity

The time and space complexity of the above algorithm is as follows.

Time Complexity

The time complexity of the algorithm is O(1)

Space Complexity

The space complexity of the algorithm is O(1)

By Using Heron’s Formula

Heron’s formula is a widely used formula to calculate the area of triangles. Here we are given the three sides of the triangle.

If a, b and c are the three sides of a triangle, respectively, then Heron’s formula is given by:

Let's look at the formula first.

herons formula

Now let’s see how to use the above formula to write a program to find area of a triangle.

Algorithm

  1. We are provided with the length of the side of the triangle.
     
  2. We will first find the semi-perimeter of the triangle.
    S = (Side a + Side b + Side c)/2
     
  3. Using Heron’s formula, we can calculate the area of the triangle.
    Area of the triangle = [root( s(a-a)(s-b)(s-c)]
     
  4. Print the value of the triangle.

Implementation

After learning the algo, write the program to find area of a triangle. Let’s see its implementation in various programming languages.

Below is the C language implementation for the above algo.

C

#include <stdio.h>
#include <math.h> 

int main()
{
    float side_a, side_b, side_c;
    
    printf("Enter the value of the side A, B, C of the triangle:");
    scanf("%f %f %f",&side_a, &side_b, &side_c);
    float s = (side_a + side_b + side_c) / 2;
    
    // Calculating the area
    float area = sqrt(s * (s - side_a) * (s - side_b) * (s - side_c));
    
    printf("The area of the triangle is :  %f ", area);
    return 0;
}

 

Output

output of c

 

Now let’s have a look at C++ program to find area of a triangle using heron's formula.

C++

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
    float side_a = 4, side_b = 7, side_c = 8;
    float area;
    float s = (side_a + side_b + side_c) / 2;
    area = sqrt(s * (s - side_a) * (s - side_b) * (s - side_c));
    cout<<"Area of Triangle= "<<area<<endl;
    return 0;
}

 

Output

output for cpp

The Java program for the above algo is as follows.

Java

public class Demo {
   public static void main(String[] args) {
   
      // Sides of a triangle
      double s1, s2, s3;
      double area, resArea;
      
      // Three sides of a triangle
      s1 = 4;
      s2 = 7;
      s3 = 8;
      area = (s1+s2+s3)/2.0d;
      resArea = Math.sqrt(area* (area - s1) * (area - s2) * (area - s3));
      System.out.println("Area of Triangle = " + resArea);
   }
}


Output

output for java

Now, let’s see algo’s implementation in JavaScript language.

JavaScript

const sides = [4, 7, 8];
const areaOfTriangle = sides => {
   const [side_a, side_b, side_c] = sides;
   const sp = (side_a + side_b + side_c) / 2;
   const aDifference = sp - side_a;
   const bDiffernece = sp - side_b;
   const cDifference = sp - side_c;
   const area = Math.sqrt(sp * aDifference * bDiffernece * cDifference);
   return area;
};
console.log("AREA OF TRIANGLE IS", areaOfTriangle(sides));


Output

output for js

The Python implementation of the above algo is as follows.

Python

side_a = 4;
side_b = 7;
side_c = 8;

# Calculating the semi-perimeter of the triangle
s = (side_a + side_b + side_c)/2;

# Calculating the area of the triangle
area = (s*(s-side_a)*(s-side_b)*(s-side_c)) ** 0.5
print('AREA OF TRIANGLE IS %f' %area)


Output

output of python

Complexity

The time and space complexity of the above algorithm is as follows.

Time Complexity

The time complexity of the algorithm is O(1)

Space Complexity

The space complexity of the algorithm is O(1)

For an Equilateral Triangle

An equilateral triangle is a type of triangle in which all sides are of the same length. The angles in between them are sure to be 60oIf you are given a triangle whose sides are equal, you can simply use the formula below to find its area.

Area of equilateral triangle = [root(3)*side*side]/4 

OR

Area of equilateral triangle =  [(1.73)*side*side]/4
(As root(3)~= 1.73)

We can use the approximate value if we do not wish to use the math function in our program.

We can use the above formula to write a program to find area of a triangle. The algorithm of this program is as follows.

Algorithm

  1. We are provided with a side of a triangle. Put it into a float variable.
     
  2. Calculate the value of the triangle by using the formula
    Area of equilateral triangle = [root(3)*side*side]/4 
     
  3. You can also use the below formula if you do not wish to use the math function.
    Area of equilateral triangle =  [(1.73)*side*side]/4
     
  4. Print the value of the triangle.

Implementation

After learning the algo, write the program to find area of a triangle. Let’s see its implementation in various programming languages.

Below is the C language implementation for the above algo.

C

#include <stdio.h>
#include <math.h>

int main()
{
    float side;
    printf("Enter the value of side of the equilateral triangle:");
    scanf("%f",&side);
    float area = (sqrt(3)/4) * (side * side);
    printf("The area of the equilateral Triangle is : %f", area);
    return 0;
}


Output

output of c

Now let’s have a look at a C++ program to find area of a triangle.

C++

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
	float side=8, area;
	area = sqrt(3)/4*(side*side);
	cout<<" The area of equilateral triangle is: "<<area<<endl;
	cout << endl;
	return 0;
}


Output

output for cpp

The Java program for the above algo is as follows.

Java

class Area {
    static double area(double side) {
        return (1.73 * side * side) / 4;
    }

    public static void main(String[] args) {
        double side = 8;
        System.out.println("Area of the equilateral triangle: " + area(side));
    }
}


Output

output for java

Note: We had used 1.73 in place of sqrt(3).

Now, let’s see algo’s implementation in JavaScript language.

JavaScript

let i,
side = 8
area = 1
for(i=1;i<=side;i++)
{
    area = (1.73*side*side)/4
}

console.log("The area of equilateral triangle is", Math.round(area*100)/100)


Output

output for js

Note: We had used 1.73 in place of sqrt(3).

The Python implementation of the above algo is as follows.

Python

side= 8  
area = ( 1.73 * side * side) / 4  
print("Area of Equilateral Triangle is: ");  
print(area); 


Output

output of python

Note: We had used 1.73 in place of sqrt(3).

Complexity

The time and space complexity of the above algorithm is as follows.

Time Complexity

The time complexity of the algorithm is O(1)

Space Complexity

The space complexity of the algorithm is O(1)

Note: Use of semicolons in python is optional. It doesn't terminate sentences. Also, it doesn't show any error while compiling.

Also read reverse a number.

Frequently Asked Questions

Why the complexities of all the above algorithms for finding the area of a triangle are O(1)?

The time complexity of the above programs is O(1). It is because the programs consist of only assignment and arithmetic operations, and all of those will be executed only once. They are also not taking any extra space for storing the value. 

What is the most used program to find area of a triangle?

The most commonly used program to find area of a triangle uses the base and height of the given triangle. Given by Area = (base*height)/2.

Is it necessary to include a maths function to do the maths operation?

C++ provides many maths functions that can be used directly in the program. Being a subset of C language, C++ derives most of these mathematical functions from math.h header of C.

What are %c and %s, and why are they used?

The %c and %s are the format specifiers. %c is used to take a character as input or to print a character. In the case of strings, %s is used as the format specifier.

Why are format specifiers used in programming languages?

Format specifiers are used for input and output. The format specifier notion allows the compiler to decide what type of data is in a variable when taking input and publishing it.

Conclusion

This article briefly discussed the program to find area of a triangle. We discussed various approaches based on the info given to us to do it. We hope this blog has helped you write the program to find area of a triangle. If you like to learn more, you can check out our articles: 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptAWS and many more! If you wish to test your skills in coding, check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

For placement preparations, you must look at the problemsinterview experiences, and interview bundles.

You can consider our paid courses to give your career an edge over others!

Happy Learning!

Previous article
Addition of two numbers in C
Next article
Program to calculate the simple interest in C
Live masterclass