Dart program to check if a year is leap year or not:
In this post, we will learn how to check if a year is leap year or not. With this program, you will learn how to use if-else in Dart to check for conditions.
The program will take one year as an input from the user and print out if this is leap year or not.
The algorithm to check for leap year works as like below:
- Check if the year is divisible by 4 or not. If not, it is not a leap year.
- If it is divisible by 4, check if it is divisible by 100 or not. If not, it is not a leap year.
- If it divisible by 4 and 100, check if it is divisible by 400 or not. If not, it is not a leap year.
So, if we follow these steps, we can find out if a given year is leap year or not.
Dart program:
Below is the complete dart program:
import 'dart:io';
bool isLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
void main() {
print("Enter a year to check : ");
int year = int.parse(stdin.readLineSync());
if (isLeapYear(year)) {
print("Leap Year");
} else {
print("Not a Leap Year");
}
}
Here,
- isLeapYear function is used to check if a year is leap year or not. It returns one boolean value. true if it is leap year and false if it is not.
- In the main function, we are taking one year as an user input. It asks the user to enter a year and calls isLeapYear with that year to check if it is leap year or not.
- Based on the return value of isLeapYear, it prints if the year is leap year or not.
You might also like:
- Dart program to concat string with integer
- How to remove string character using index in Dart
- Dart check for any or every element in a list satisfy a given condition
- Dart program to check if a list contains a specific element or not
- How to shuffle a dart list
- Encoding/decoding JSON in Dart explanation with examples