C program to check if a year is leap year or not

Category: C Program
Tags: #cprogram#ifelse#conditional

Learn how to create a C program to determine leap years. Explore the code logic that identifies whether a given year is a leap year or not. Understand leap year rules and utilize C programming concepts for accurate year verification.

In this article, we'll explore how to create a simple C program to check whether a given year is a leap year.

Understanding Leap Years

A leap year is a year that is evenly divisible by 4. However, there are exceptions to this rule:

  • Years divisible by 100 are not leap years unless they are also divisible by 400.
  • For example, 2000 was a leap year because it is divisible by both 100 and 400, while 1900 was not a leap year because it is divisible by 100 but not by 400.

C program to check if a year is leap year or not

Let's delve into the C programming language to create a program that checks whether a user-input year is a leap year or not.

#include <stdio.h>

int main() {
    int year;

    // Input from the user
    printf("Enter a year: ");
    scanf("%d", &year);

    // Checking leap year condition
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        printf("%d is a leap year.", year);
    } else {
        printf("%d is not a leap year.", year);
    }

    return 0;
}

Output

Enter a year: 2000
2000 is a leap year.

Understanding the Code

  1. Header File and Main Function: The program starts by including the necessary header file <stdio.h> and defining the main() function.
  2. User Input: The user is prompted to enter a year, which is stored in the variable year using scanf().
  3. Leap Year Check: The program checks for leap year conditions using the modulo operator %. If the year meets the leap year criteria (divisible by 4 but not by 100, or divisible by 400), it is identified as a leap year.
  4. Output: Depending on the leap year check results, appropriate messages are displayed to the user.