Advertisement
Razhagal

Perimeter and Area of Polygon

Mar 31st, 2014
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. class Point
  8. {
  9.     public int X { get; set; }
  10.     public int Y { get; set; }
  11. }
  12.  
  13. class PerimeterAndAreaOfPolygon
  14. {
  15.     static double CalculateDistance(int x1, int y1, int x2, int y2)
  16.     {
  17.         int distanceX = x2 - x1;
  18.         int distanceY = y2 - y1;
  19.  
  20.         double distance = Math.Sqrt((distanceX * distanceX) + ( distanceY * distanceY));
  21.         return distance;
  22.     }
  23.  
  24.     static double PolygonPerimeter(Point[] perimeter)
  25.     {
  26.         double peri = 0;
  27.         for (int i = 0; i < perimeter.Length - 1; i++)
  28.         {
  29.             peri += CalculateDistance(perimeter[i].X, perimeter[i].Y,
  30.                                       perimeter[i + 1].X, perimeter[i + 1].Y);
  31.         }
  32.         return peri;
  33.     }
  34.  
  35.     static double PolygonArea(int[,] matrix, int rows)
  36.     {
  37.         double matrixResult;
  38.         double leftSideSum = 0;
  39.         double rightSideSum = 0;
  40.        
  41.         for (int i = 0; i < rows - 1; i++)
  42.         {
  43.             leftSideSum += (matrix[i, 0] * matrix[i + 1, 1]);
  44.             rightSideSum += (matrix[i, 1] * matrix[i + 1, 0]);
  45.         }
  46.  
  47.         matrixResult = Math.Abs((leftSideSum - rightSideSum) / 2);
  48.  
  49.         return matrixResult;
  50.     }
  51.     static void Main()
  52.     {
  53.         int pointsNumber = int.Parse(Console.ReadLine());
  54.         int[,] matrix = new int[pointsNumber, 2];
  55.  
  56.         Point[] perimeter = new Point[pointsNumber];
  57.        
  58.         for (int i = 0; i < pointsNumber; i++)
  59.         {
  60.             string pointCoordinates = Console.ReadLine();
  61.             string[] coordinate = pointCoordinates.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  62.            
  63.             perimeter[i] = new Point() { X = int.Parse(coordinate[0]), Y = int.Parse(coordinate[1]) };
  64.             matrix[i, 0] = int.Parse(coordinate[0]);
  65.             matrix[i, 1] = int.Parse(coordinate[1]);
  66.         }
  67.        
  68.         Console.WriteLine("The Perimeter of the polygon is {0:F2}", PolygonPerimeter(perimeter));
  69.         Console.WriteLine("The Area of the polygon is {0:F2}", PolygonArea(matrix, pointsNumber));
  70.  
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement