I have an array of numbers typed Int
.
I want to loop through this array and determine if each number is odd or even.
How can I determine if a number is odd or even in Swift?
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.
If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd.
We given a task to create a swift function to generate and return an array of an odd number for a given number of element. import Foundation func generate(len: Int) -> [Int] { let count = len. count - 1 var oddArray = [Int]() for i in 0 ... count{ let val = len[i] % 2 if val != 0 { oddArray.
var myArray = [23, 54, 51, 98, 54, 23, 32]; for myInt: Int in myArray{ if myInt % 2 == 0 { println("\(myInt) is even number") } else { println("\(myInt) is odd number") } }
Use the %
Remainder Operator (aka the Modulo Operator) to check if a number is even:
if yourNumber % 2 == 0 { // Even Number } else { // Odd Number }
or, use remainder(dividingBy:)
to make the same check:
if yourNumber.remainder(dividingBy: 2) == 0 { // Even Number } else { // Odd Number }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With