Program to Check Leap Year - (C# Basic Programs)
A leap year is a year that is divisible by 4, except for years that are divisible by 100 but not divisible by 400. In this tutorial, we will discuss a C# program to check if a given year is a leap year or not.
Syntax
The syntax for checking whether a year is a leap year or not in C# is as follows:
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
Console.WriteLine(year + " is a leap year");
}
else {
Console.WriteLine(year + " is not a leap year");
}
Example
using System;
namespace LeapYearProgram
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a year: ");
int year = int.Parse(Console.ReadLine());
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
Console.WriteLine(year + " is a leap year");
}
else {
Console.WriteLine(year + " is not a leap year");
}
Console.ReadLine();
}
}
}
Output
Enter a year: 2024
2024 is a leap year
Explanation
The program prompts the user to enter the year they want to check. The program then evaluates whether the given year is a leap year or not. If the given year is divisible by 4 and not divisible by 100, or is divisible by 400, the program will output that the year is a leap year. If not, the program will output that the year is not a leap year.
Use
Checking whether a year is a leap year or not in C# is a basic programming skill that can be used in various applications. It helps in calculations related to time, dates and financial applications where interest is paid on a yearly basis and the number of days in a year is important.
Summary
In this tutorial, we discussed a C# program to check whether a given year is a leap year or not. We presented the syntax, example, explanation, and use of C# programming to check leap year. By practicing these exercises, programmers can improve their problem-solving and C# programming skills.