C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
For: We use a for-loop over the numbers 0 through 5 inclusive. We test whether these numbers are even and print the results.
Note: Negative numbers are correctly supported here. A negative number can be evenly divisible by 2.
Swift program that finds even numbers
func even(number: Int) -> Bool {
// Return true if number is evenly divisible by 2.
return number % 2 == 0
}
// Test the parity of these numbers.
for i in 0...5 {
let result = even(i)
// Display result.
print("\(i) = \(result)")
}
Output
0 = true
1 = false
2 = true
3 = false
4 = true
5 = false
Swift program that finds odd numbers
func odd(number: Int) -> Bool {
// Divide number by 2.
// ... If remainder is 1, we have a positive odd number.
// ... If remainder is -1, it is odd and negative.
// ... Same as "not even."
return number % 2 != 0
}
for i in -3...3 {
let result = odd(i)
print("\(i) = \(result)")
}
Output
-3 = true
-2 = false
-1 = true
0 = false
1 = true
2 = false
3 = true