Odd and Even NumbersFind odd and even numbers with modulo division. Handle negative numbers.
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.
Detail 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(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(i) print("\(i) = \(result)") }
-3 = true -2 = false -1 = true 0 = false 1 = true 2 = false 3 = true
A 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2023 Sam Allen.