Program to find area of triangle in C/C++

Program to find area of triangle in C/C++

This is a program to find the area of a triangle by taking coordinates of its vertices.

1. Program in C

#include<stdio.h>
#include<math.h>
int main() {
  int x1, x2, x3, y1, y2, y3;
  float a, b, c, s, area;
  printf("\n Enter co-ordinates of 1st point: ");
  scanf("%d%d", & x1, & y1);
  printf("\n Enter co-ordinates of 2nd point: ");
  scanf("%d%d", & x2, & y2);
  printf("\n Enter co-ordinates of 3rd point: ");
  scanf("%d%d", & x3, & y3);
  a = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  b = sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3));
  c = sqrt((x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1));
  s = (a + b + c) / 2.0;
  area = sqrt(s * (s - a) * (s - b) * (s - c));
  printf("Area= %f", area);
  return 0;
}

2. Program in C++

#include<iostream>
#include<math.h>
using namespace std;
int main() {
  int x1, x2, x3, y1, y2, y3;
  float a, b, c, s, area;
  cout << "\n Enter co-ordinates of 1st point: ";
  cin >> x1 >> y1;
  cout << "\n Enter co-ordinates of 2nd point: ";
  cin >> x2 >> y2;
  cout << "\n Enter co-ordinates of 3rd point: ";
  cin >> x3 >> y3;
  a = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  b = sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3));
  c = sqrt((x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1));
  s = (a + b + c) / 2.0;
  area = sqrt(s * (s - a) * (s - b) * (s - c));
  cout << "Area= " << area;
  return 0;
}

3. Output-

area of triangle

4. Explanation-

First we calculate all 3 sides by using Pythagoras theorem.
a = √((x1-x2​)² + (y1-y2​)²)
The semi perimeter of the triangle is half its perimeter. So adding 3 sides and dividing by 2 we semi perimeter.
s = (a + b + c)/2
Lastly we calculate the area of triangle by Heron’s formula. It gives the area of a triangle when the length of all three sides are known.
area = s(s−a)(s−b)(s−c)​

5. Parts of program-

1. #include is a pre-processor directive. It is used to include header files.
2. stdio/iostream is header file which has certain commands that c/c++ supports. E.g. return, main, etc.
3. .h is an extension for header file.
4. int is data type. It indicates that the program returns a value.
5. main() is main function that indicates the compiler that the user written programs starts from here.
6. print/cout is the keyword use to print a message.
7. scanf/cin is the keyword use to store values in variables.
8. return statement is use to return a value. If any error occurs the program will return 0.

Conclusion-

This was the program to find area of triangle in C/C++. We hope it was clear to you. If you find it useful then do share it with your programming buddies and friends. Also if you have any doubt regarding any post do tell us in the comment section.

For daily updates do follow us on Instagram. Visit again!

ErrorFreeProgram.

Leave a Reply

Your email address will not be published. Required fields are marked *