C# is a general-purpose programming language, which means we can tackle various computational problems through it. For example, we can build a program to calculate a rectangle’s area and perimeter.
To achieve our objective, we need to know the width and length of the rectangle. Therefore, our program will accept two arguments separated by a space. For example, to describe a rectangle with a width of 14 cm and a length of 5 cm, we use the following input:
14 5
Let’s calculate the area and perimeter of a rectangle.
A rectangle’s area is calculated by multiplying its width by its length. The
CalculateRectangleArea
method needs to accept two parameters and return the result of the multiplication. This method provides the Main
method with the length and width that it obtained from the user:
using System;class Program{static void Main(){string[] args = Console.ReadLine().Split();if (args.Length != 2){Console.WriteLine("Please, provide the width and the length");return;}double width;double length;try{width = double.Parse(args[0]);length = double.Parse(args[1]);}catch{Console.WriteLine("Width and length must be numbers.");return;}var area = CalculateRectangleArea(width, length);Console.WriteLine($"Given a rectangle with the width of {width} and the length of {length}");Console.WriteLine($"Area: {area}");}static double CalculateRectangleArea(double width, double length){return width * length;}}
Enter the input below
The perimeter is the sum of all sides. Since the opposing sides are equal to each other in a rectangle, we only need to know the width and the length to be able to calculate the perimeter:
using System;class Program{static void Main(){string[] args = Console.ReadLine().Split();if (args.Length != 2){Console.WriteLine("Please, provide the width and the length");return;}double width;double length;try{width = double.Parse(args[0]);length = double.Parse(args[1]);}catch{Console.WriteLine("Width and length must be numbers.");return;}var perimeter = CalculateRectanglePerimeter(width, length);Console.WriteLine($"Given a rectangle with the width of {width} and the length of {length}");Console.WriteLine($"Perimeter: {perimeter}.");}static double CalculateRectanglePerimeter(double width, double length){return (width * 2) + (length * 2);}}
Enter the input below