TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to SWIFT

Swift Odd and Even Numbers

Find 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.

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
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.
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
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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf