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