- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find the Centroid of the Triangle in C++
In this problem, we are given a 2D array that denotes coordinates of three vertices of the triangle. Our task is to create a program to find the Centroid of the Triangle in C++.
Centroid of a triangle is the point at which the three medians of the triangles intersect.
Median of a triangle is the line that connects the vertex of the triangle with the center point of the line opposite to it.
Let’s take an example to understand the problem,
Input
(-3, 1), (1.5, 0), (-3, -4)
Output
(-3.5, -1)
Explanation
Centroid (x, y) = ((-3+2.5-3)/3, (1 + 0 - 4)/3) = (-3.5, -1)
Solution Approach
For solving the problem, we will use the geometrical formula for the centroid of the triangle.
For points (ax, ay), (bx, by), (cx, cy)
Centroid, x = (ax + bx + cx) / 3 y = (ay + by + cy) / 3
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int main() { float tri[3][2] = {{-3, 1},{1.5, 0},{-3, -4}}; cout<<"Centroid of triangle is ("; cout<<((tri[0][0]+tri[1][0]+tri[2][0])/3)<<" , "; cout<<((tri[0][1]+tri[1][1]+tri[2][1])/3)<<")"; return 0; }
Output
Centroid of triangle is (-1.5 , -1)
Advertisements