Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a number is odd or even in Swift?

Tags:

ios

swift

parity

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?

like image 846
Asif Bilal Avatar asked Jun 05 '14 09:06

Asif Bilal


People also ask

How do you check 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.

How do you check if a number is even or 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.

How do you generate odd numbers in swift?

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.


2 Answers

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")   } } 
like image 153
Charith Nidarsha Avatar answered Sep 20 '22 12:09

Charith Nidarsha


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 } 
like image 45
num8er Avatar answered Sep 20 '22 12:09

num8er