Swift Program to Check Even or Odd

1. Introduction

Determining if a number is even or odd is one of the foundational concepts in mathematics, and it serves as a crucial building block in programming logic. This guide will walk you through a Swift program that checks and displays whether a number is even or odd.

2. Program Overview

The goal of this Swift program is to inspect an integer and discern whether it's even or odd. The logic is straightforward: an even number is perfectly divisible by 2 with no remainder, while an odd number leaves a remainder of 1 when divided by 2.

3. Code Program

// Declare the number to be checked
let number = 7

// Check if the number is even or odd
if number % 2 == 0 {
    print("\(number) is even.")
} else {
    print("\(number) is odd.")


7 is odd.

4. Step By Step Explanation

1. let number = 7: We begin by declaring a constant named number and assigning it the value 7.

2. if number % 2 == 0 { ... } else { ... }: This conditional statement checks if the number is even or odd. The modulo operation (%) returns the remainder when number is divided by 2. If the remainder is 0, then the number is even; otherwise, it's odd.

3. print("\(number) is even.") and print("\(number) is odd."): Inside the conditional branches, the appropriate message is printed to the console based on whether the number is even or odd. The print function uses string interpolation to embed the value of the number constant within the output string.