C# Program to Check if a given Year is a Leap Year or Not.

A leap year is a year that contains an extra day, February 29th, making it 366 days instead of the usual 365 days. Leap years are important to ensure that our calendar remains in sync with the solar year.

In this article, we will explore how to write a C# program to determine if a given year is a leap year or not.


Problem Statement.

Write a C# program to check whether a given year is a leap year or not.


Leap Year Criteria

A year is a leap year if it meets one of the following criteria:

  • The year is evenly divisible by 4, but not divisible by 100.
  • The year is divisible by 400.


Example

Let's say we want to check whether the year 2024 is a leap year or not.

Steps to check Leap Year:

  • Check if the year is divisible by 4: 2024 % 4 = 0
  • Check if the year is not divisible by 100: 2024 % 100 != 0
  • Since both conditions are met, 2024 is a leap year.


C# Code to Check a Leap Year.

//C-sharp program to check given year is leap year or not
using System;

class Program {
    static void Main(string[] args) {
        Console.Write("Enter a year: ");
        int year = int.Parse(Console.ReadLine());

        bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

        if (isLeapYear) {
            Console.WriteLine($"{year} is a leap year.");
        } else {
            Console.WriteLine($"{year} is not a leap year.");
        }
    }
}
Output:
Enter a year: 2023
2023 is not a leap year.

Explanation:

1. We take input from the user for the year.
2. We use the ternary operator (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) to check whether the year meets the leap year criteria.
3. If the condition is true, we output that the year is a leap year. Otherwise, we output that it is not a leap year.

⚡ 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