Swift practice: List all numbers between 1 and 100 that are divisible by 7 without remainder

This is a Swift code that uses a “for” loop to iterate over a range of numbers from 1 to 100, checking if each number is divisible by 7.

So, this code prints all numbers between 1 and 100 that are divisible by 7.

var number = 0

for number in 1...100 {
    if number % 7 == 0 {
        print(number)
    } else {
        continue
    }
}

/* Output
7
14
21
28
35
42
49
56
63
70
77
84
91
98
*/

Quick notes

  1. The “var number = 0” initializes a variable called “number” with an initial value of 0.  Note that this variable is not necessarily needed for the loop because it will be overwritten by the loop.
  2. The “for number in 1…100” statement sets up a loop that will iterate over a range of numbers from 1 to 100.
  3. The “if number % 7 == 0” statement checks if the current number in the loop is divisible by 7 using the modulo operator “%“.
  4. If the current number is divisible by 7, the “print(number)” statement will print that number to the console.
  5. If the current number is not divisible by 7, the “continue” statement will skip to the next iteration of the loop, without executing the remaining code.

Leave a Reply

Your email address will not be published. Required fields are marked *