C Program to Check Leap Year

1. Introduction

A leap year, in the Gregorian calendar, comprises 366 days instead of the usual 365. This extra day is added in February, making it 29 days long. Leap years are introduced to keep our calendar year synchronized with the astronomical year. In this guide, we will create a C program that determines whether a given year is a leap year or not.

2. Program Overview

Our program will:

1. Prompt the user to input a year.

2. Determine if the provided year is a leap year based on specific conditions.

3. Display the result to the user.

3. Code Program

#include <stdio.h>  // Include the Standard I/O library

int main() {  // Begin the program

    int year;  // Declare a variable to store the year

    // Ask the user to input a year
    printf("Enter a year: ");
    scanf("%d", &year);  // Capture the input year

    // Use conditions to ascertain if it's a leap year
    if(year % 4 == 0) {
        if(year % 100 == 0) {
            if(year % 400 == 0)
                printf("%d is a leap year.\n", year);  // Year divisible by 400 is a leap year
            else
                printf("%d is not a leap year.\n", year);  // Year divisible by 100 but not by 400 isn't a leap year
        }
        else
            printf("%d is a leap year.\n", year);  // Year divisible by 4 but not by 100 is a leap year
    }
    else
        printf("%d is not a leap year.\n", year);  // Year not divisible by 4 isn't a leap year

    return 0;  // Finish the program successfully
}

Output:

Enter a year: 2020
2020 is a leap year.

4. Step By Step Explanation

1. #include <stdio.h>: This incorporates the standard input and output library.

2. int main(): The main function where our program starts its execution.

3. Variable Declaration:

  • year: This will store the year input by the user.

4. User Input:

  • We prompt the user to provide a year.
  • The scanf function then reads the user's input.

5. Leap Year Determination:

- A year is a leap year if:

  • It's divisible by 4 (i.e., year % 4 == 0).
  • However, if it's divisible by 100 (i.e., year % 100 == 0), it must also be divisible by 400 to be a leap year (i.e., year % 400 == 0).

- We employ nested if-else conditions to test these criteria and deduce whether the input year is a leap year or not.

6. Output: The program subsequently conveys if the entered year is a leap year.

Utilizing the above logic, we can effectively determine the leap year status for any provided year, ensuring our date-based computations remain accurate.

Comments