Check if Number is Odd
To check if a given number is odd, use the condition that the number leaves a reminder of 1
when divided with 2
.
In the following program, we will define a function isOdd()
that accepts an integer, and returns true
if the number is odd or false
if the number is not even.
main.swift
import Foundation
func isOdd(_ n: Int) -> Bool {
return n % 2 == 1
}
print("Is 3 odd? \(isOdd(3))")
print("Is 8 odd? \(isOdd(8))")
Program Output
Is 3 odd? true
Is 8 odd? false
Summary
Summarising this tutorial, we learned how to check if a given number is odd or not.