Wednesday, April 30, 2025

C Program - Check Leap Year with C Programming Language

 This C program determines whether a given year is a leap year or not.

#include <stdio.h>

int main()
{

    int year;

    while (1)
    {

        printf("Enter a Year: ");
        scanf("%d", &year);

        if (year % 4 != 0)
        {
            printf("NOT Leap Year \n");
        }
        else if (year % 100 != 0)
        {
            printf("Leap Year \n");
        }
        else if (year % 400 != 0)
        {
            printf("NOT Leap Year \n");
        }
        else
        {
            printf("Leap Year \n");
        }
    }

    return 0;
}

Result: 

Enter a Year: 2023
NOT Leap Year
Enter a Year: 2020
Leap Year
Enter a Year: 2025
NOT Leap Year
Enter a Year:

Here is a line-by-line explanation of the code: 

#include <stdio.h>

This line includes the standard input/output library that allows the program to interact with the user through the console. 

int main()
{

This is the starting point of the program and the main function. 

    int year;

Declare an integer variable named year to hold the year to be checked. 

    while (1)
    {

This creates an infinite loop that will continue to ask the user for a year until the program is terminated. 

        printf("Enter a Year: ");
        scanf("%d", &year);

This line prints the prompt message to the console, waits for the user to input a value, and stores the value in the year variable. 

        if (year % 4 != 0)
        {
            printf("NOT Leap Year \n");
        }

If the remainder of year divided by 4 is not equal to 0, then the year is not divisible by 4 and, therefore, is not a leap year. In that case, the program prints "NOT Leap Year" to the console. 

        else if (year % 100 != 0)
        {
            printf("Leap Year \n");
        }

If the year is divisible by 4, but not by 100, it is a leap year. In that case, the program prints "Leap Year" to the console. 

        else if (year % 400 != 0)
        {
            printf("NOT Leap Year \n");
        }

If the year is divisible by 100 but not by 400, it is not a leap year. In that case, the program prints "NOT Leap Year" to the console. 

        else
        {
            printf("Leap Year \n");
        }

If the year is divisible by both 100 and 400, it is a leap year. In that case, the program prints "Leap Year" to the console. 

    }

The end of the while loop. 

    return 0;
}

The program ends and returns the integer value 0 to the operating system.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...