Artificial Intelligence
Please fill the required field.

hello, can you do leap year code c sharp


Certainly! Here’s a simple C# program that checks if a given year is a leap year: ```csharp using System; class Program { static void Main() { Console.WriteLine("Enter a year:"); int year; // Input validation while (!int.TryParse(Console.ReadLine(), out year)) { Console.WriteLine("Invalid input. Please enter a valid year:"); } if (IsLeapYear(year)) { Console.WriteLine($"{year} is a leap year."); } else { Console.WriteLine($"{year} is not a leap year."); } } static bool IsLeapYear(int year) { // A year is a leap year if: // 1. It is divisible by 4. // 2. If it is divisible by 100, it must also be divisible by 400. if (year % 4 == 0) { if (year % 100 == 0) { return year % 400 == 0; } return true; } return false; } } ``` ### How It Works: 1. The program prompts the user to enter a year. 2. It then checks if the input is a valid integer. 3. The `IsLeapYear` method determines if the given year is a leap year based on the rules: - A year is a leap year if it is divisible by 4. - If it is divisible by 100, it must also be divisible by 400 to be considered a leap year. 4. Finally, it outputs whether the year is a leap year or not. ### How to Run: - Copy the code into a C# development environment or an online C# compiler. - Run the program, input a year, and observe the result. Update (2025-07-21): Sure! A leap year occurs in the Gregorian calendar if the following conditions are met: 1. The year is divisible by 4. 2. If the year is divisible by 100, it is **not** a leap year, unless: 3. The year is also divisible by 400, in which case it is a leap year. Here's a simple C# code snippet to check if a given year is a leap year: ```csharp using System; class LeapYearChecker { static void Main() { Console.WriteLine("Enter a year:"); int year; // Try to parse the input to an integer if (int.TryParse(Console.ReadLine(), out year)) { if (IsLeapYear(year)) { Console.WriteLine($"{year} is a leap year."); } else { Console.WriteLine($"{year} is not a leap year."); } } else { Console.WriteLine("Please enter a valid year."); } } static bool IsLeapYear(int year) { // Check if the year is a leap year return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } } ``` ### How to Use the Code 1. Copy the code into a C# environment (like Visual Studio or any online C# compiler). 2. Run the program. 3. Input a year when prompted, and the program will tell you whether it is a leap year or not. ### Explanation - The program starts by prompting the user for a year. - It checks if the input can be parsed into an integer. - The `IsLeapYear` method encapsulates the leap year logic using the rules outlined. - Finally, it prints the result based on the condition evaluated in the `IsLeapYear` method.