easy
0 views

Polygon Perimeter

Calculate and print the perimeter of a polygon given the lengths of its N sides

Understand the Problem

Problem Statement

Given a polygon with N sides, calculate and print the perimeter of the polygon by summing the lengths of all its sides.

Constraints

  • 3 ≤ N ≤ 100 (number of sides)
  • 1 ≤ side length ≤ 999999 (each side length is a positive integer)

Examples

Example 1
Input
3
100
60
70
Output
230
Explanation

The polygon has 3 sides with lengths 100, 60, and 70. The perimeter is 100 + 60 + 70 = 230.

Example 2
Input
5
300
100
100
200
200
Output
900
Explanation

The polygon has 5 sides with lengths 300, 100, 100, 200, and 200. The perimeter is 300 + 100 + 100 + 200 + 200 = 900.

Solution

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    
    int perimeter = 0;
    int side;
    
    for (int i = 0; i < n; i++) {
        scanf("%d", &side);
        perimeter += side;
    }
    
    printf("%d", perimeter);
    
    return 0;
}
Time:O(N) - We iterate through N sides once
Space:O(1) - We only use a constant amount of extra space
Approach:

C Solution Explanation:

  1. Read the number of sides N using scanf
  2. Initialize perimeter to 0 to accumulate the sum
  3. Use a for loop to iterate N times
  4. In each iteration, read one side length and add it to perimeter
  5. After the loop, print the total perimeter using printf

Visual Explanation

Loading diagram...