C# is a powerful and versatile programming language that excels in developing a wide range of applications. In this article, we will delve into creating a C# program that efficiently calculates the number of days in a given month. This functionality is essential for applications involving date and time computations, such as scheduling and calendar systems.
Objective: The primary objective of this C# program is to take user input for a specific month and year and output the corresponding number of days in that month, accounting for factors like leap years.
Code Implementation: Let’s explore the C# code for achieving this goal:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | using System; class DaysInMonthProgram { static void Main() { // Get user input for month Console.Write("Enter the month (1-12): "); int month = Convert.ToInt32(Console.ReadLine()); // Get user input for year Console.Write("Enter the year: "); int year = Convert.ToInt32(Console.ReadLine()); // Check if the month is valid if (month < 1 || month > 12) { Console.WriteLine("Invalid month. Please enter a month between 1 and 12."); } else { // Call the method to get the number of days int daysInMonth = GetDaysInMonth(month, year); // Display the result Console.WriteLine($"Number of days in the specified month: {daysInMonth}"); } } // Method to calculate the number of days in a month private static int GetDaysInMonth(int month, int year) { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: // Check for leap year if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return 29; // Leap year } else { return 28; // Non-leap year } default: return -1; // Invalid month } } } |
Explanation:
- User Input:
- We use
Console.ReadLine()
to get input from the user for the month and year.
- We use
- Validation:
- The code checks if the entered month is within the valid range (1-12).
- Method for Calculating Days:
- The
GetDaysInMonth
method is responsible for calculating the number of days based on the given month and year.
- The
- Switch Statement:
- A switch statement is used to handle different cases for months with 31, 30, or 28/29 days (leap year consideration).
- Displaying Result:
- The program displays the calculated number of days in the specified month.
Conclusion: This C# program showcases how to create a user-friendly application for determining the number of days in a month. The combination of user input, conditional statements, and a method for calculations demonstrates the flexibility and clarity of C# in handling date-related tasks.