Calculating the area of a rectangle is a fundamental mathematical operation often encountered in programming. In this article, we'll explore how to write a simple C# program to calculate the area of a rectangle using user-provided input.
Problem Statement: Write a C# program that takes the length and width of a rectangle as user input and calculates its area. Display the result to the user.
Example:
Input: Length (L): 8 Width (W): 5 Output: The area of the rectangle is: 40 Explanation: Area = L x W = 8 x 5 = 40
C# Code to Calculate Area of Rectangle.
//C-sharp code to calculate area of Rectangle using System; namespace RectangleAreaCalculator { class Program { static void Main(string[] args) { // Read length and width from the user Console.Write("Enter the length of the rectangle: "); double length = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter the width of the rectangle: "); double width = Convert.ToDouble(Console.ReadLine()); // Calculate the area double area = length * width; // Display the area Console.WriteLine($"The area of the rectangle is: {area}"); // Keep the console window open Console.ReadLine(); } } }
Enter the length of the rectangle: 8
Enter the width of the rectangle: 4
The area of the rectangle is: 32
Code Explanation:
In the above C-sharp program, Convert.ToDouble() is used to convert the user input from strings to double values for calculations. We also need to add Console.ReadLine() at the end keeps the console window open until the user presses Enter.
This program demonstrates basic user input, data conversion, arithmetic operation, and output formatting in C#.
No comments:
Post a Comment