Kotlin – Check Leap Year

Kotlin – Check if Given Year is Leap Year

In Kotlin, a leap year is a year that is divisible by 4 but not divisible by 100, except if it is also divisible by 400. This tutorial will guide you through the process of writing a Kotlin program to check if a given year is a leap year.

Example

Step 1: Define the Year

Start by defining the year you want to check for leap year.

val year = 2024 // Change the value of year as needed

Step 2: Check if Year is Leap Year

Create a function to check if the given year is a leap year based on the leap year rules.

fun isLeapYear(year: Int): Boolean {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

Step 3: Print the Result

Call the isLeapYear function with the year as the argument and print the result.

if (isLeapYear(year)) {
    println("$year is a leap year.")
} else {
    println("$year is not a leap year.")
}

Complete Kotlin Program

The following is the complete Kotlin program to check if a given year is a leap year.

Kotlin Program

fun main() {
    val year = 2024 // Change the value of year as needed

    if (isLeapYear(year)) {
        println("$year is a leap year.")
    } else {
        println("$year is not a leap year.")
    }
}

fun isLeapYear(year: Int): Boolean {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

Output

2024 is a leap year.

Summary

By following these steps and using the leap year rules, you can easily check if a given year is a leap year in Kotlin.