Home
Swift
Odd and Even Numbers
Updated Aug 22, 2023
Dot Net Perls
Odd, even. The parity of a number is sometimes important. 0 is even. 1 is odd. With odd and even checks, we can alternate a test or computation in a loop.
With modulo division in Swift, we can tell the parity of a number. If a modulo division by 2 returns 0, we have an even number. If it does not, we have an odd.
Even. Let us begin with the even() func. This returns a bool indicating whether the number is even. It returns the result of an expression—whether the number is evenly divisible by 2.
Start 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.
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(number: i) // Display result. print("\(i) = \(result)") }
0 = true 1 = false 2 = true 3 = false 4 = true 5 = false
Odd. An odd number is not even. It can be negative. Here we test for "not equal to zero." We do not test for a remainder of 1, as this would not support negative 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(number: i) print("\(i) = \(result)") }
-3 = true -2 = false -1 = true 0 = false 1 = true 2 = false 3 = true
Summary. Usually the parity of a number is not directly needed. But with even() and odd() we can test for even numbers and odd ones to change how we handle values in a loop.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 22, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen