Find number of diagonals in n sided convex polygon in C++

C++Server Side ProgrammingProgramming

Suppose we have a number n, and we have to find the number of diagonals for n sided convex polygon. So if the n = 5, then diagonals count will be 5.

As this is n-sided convex polygon, from each vertex we can draw n – 3 diagonals leaving two sided adjacent vertices and itself. So for n vertices, it will be n*(n-3), but as we are considering twice, so it will be n(n – 3)/2.

Example

 Live Demo

#include<iostream>
using namespace std;
int diagonalCount(int n) {
   return n * (n - 3) / 2;
}
int main() {
   int n = 8;
   cout << n << " sided convex polygon has " << diagonalCount(n) << " diagonals";
}

Output

8 sided convex polygon has 20 diagonals
raja
Published on 18-Dec-2019 12:43:29
Advertisements