Basic C# Console

C# Calculate Rectangle Area

 This article presents a simple C# program to calculate the area of a rectangle based on user input. It illustrates how to use basic arithmetic operations and user input handling, making it a great example for beginners learning programming.


Code Example

Below is the complete C# code for calculating the area of a rectangle

Explanation of the Code

  1. User Input:
    • The program prompts the user to enter the length and width of the rectangle
  • Console.ReadLine() takes the input as a string, and Convert.ToInt32() converts it into an integer.

Calculation:

  • The formula for the area of a rectangle is: Area=Length×Width
  • This is implemented in the code as
  • The calculated area is displayed using
  • The {0} is a placeholder for the value of the area variable, which is passed after the string.

Pause Program:

  • The Console.ReadKey() at the end keeps the console window open until a key is pressed, allowing the user to view the result.

Output:

area-of-rectangle

Key Concepts

  1. Arithmetic Operations:
    • The program demonstrates the use of the multiplication operator (*) to calculate the area.
  2. Input Conversion:
    • The Convert.ToInt32() method ensures the user input is converted to an integer type for mathematical calculations.
  3. Formatted Output:
    • The Console.WriteLine() method with placeholders provides a clean and readable output.

Enhancements

  1. Input Validation:
    • To make the program more robust, you can validate the input to ensure the user enters valid integers:

Floating-Point Support:

  • Modify the program to accept floating-point numbers for more precise calculations
  1. Perimeter Calculation:
    • You can extend the program to calculate and display the perimeter of the rectangle as well: Perimeter=2×(Length+Width)
  2. User-Friendly Interface:
    • Add labels to clearly separate input prompts and results for better readability.

Conclusion

This simple program demonstrates how to calculate the area of a rectangle in C# using basic arithmetic and user input. It serves as an excellent starting point for understanding input handling and basic mathematical operations in programming.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.