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
70Output
230Explanation
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
200Output
900Explanation
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:
- Read the number of sides N using
scanf - Initialize
perimeterto 0 to accumulate the sum - Use a for loop to iterate N times
- In each iteration, read one side length and add it to perimeter
- After the loop, print the total perimeter using
printf
Visual Explanation
Loading diagram...