Introduction :
Dart integer class contains two properties to check if a number is even or odd. We can check these properties to find out quickly if a number is odd or even. In this tutorial, I will show you how to do that :
isEven and isOdd :
isEven and isOdd are two boolean values that you can access in an integer variable in dart. Just check for these values to find out if a number is odd or even.
In the below example, we will take one number as input from the user and find out if it is odd or even.
Example program :
import 'dart:io';
void main() {
int? number;
print("Enter a number : ");
var data = stdin.readLineSync();
number = int.tryParse(data ?? '-1');
if (number == null) {
print("Invalid input.");
} else if (number.isEven) {
print("$number is an even number");
} else if (number.isOdd) {
print("$number is an odd number");
}
}
Sample Output :
Enter a number :
12
12 is an even number
Enter a number :
13
13 is an odd number
Note that it will also work for negative numbers. For example, if your number is -12, it will print as an even number.
You might also like:
- Different ways to insert items to a list in dart
- Different ways to remove items from a dart list
- Dart program to swap two user given numbers
- Constants defined in dart-math library
- How to check if a string contains a number in Dart
- How to get the current date-time in Dart
- Dart program to find the absolute value of a number