C# Program to Calculate Area of Rectangle.

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();
        }
    }
}
Output:
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#. 

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS