“Striving for success without hard work is like trying to harvest where you haven’t planted.
Agenda
- For Loop
- While Loop
- Break and Continue
- Checkpoint 3
For Loop
Loops can be used to iterate through a collection data type.
Syntax:
for loop_variable in list {
Statements
}
You can use loop_variable to traverse through the list in order. In the below example, we use loop variable “l” to iterate through the array letters.
let letters = ["a","b","c"]for l in letters {
print(l)
}
Range of numbers
To print a range of numbers say for example 1 to 12, you can follow the below example.
for i in 1...12 {
print(i)
}
loop variable can also be use to perform arithmetic operations.
for i in 1...12 {
print(i*2)
}
Instead of using the numbers, you can use constants or variables as well for the range.
let left = 1let right = 12for i in left...right {print(i)}
Nested For Loops
for i in 1...12 {
print("The \(i) times table:")
for j in 1...12 {
print(" \(j) x \(i) is \(j * i)")
}
print()
}
Exclude upper limit
for i in 1..<5 {
print(i)
}
This code will print only from 1 to 4 and will not run for i=5. This can be very helpful when you are iterating through an array by using the count of items in an array.
While Loop
While loop will continue to execute the loop body until the condition is false.
var countdown = 10
while countdown > 0 {
print("\(countdown)…")
countdown -= 1
}
print("Blast off!")
Unlike in for loop, you will have to control counter manually. So depending upon the case, you will either increase or decrease the counter.
Continue and Break
Continue
If you are in a situation where you loop should just skip executing at particular conditions, use Continue.
Let us take an example where we are printing numbers in range of 1 to 10 but we want to skip 5.
for i in 1...10 {
if i== 5 {
continue}
print(i)
}
Break
On contrary, if you want to skip rest of the loop iterations after meeting a condition, use break. This will exit the loop.
Let us consider an example where we are printing numbers from 1 to 10 and want to break the loop after 5.
for i in 1...10 {
if i== 5 {
break}
print(i)
}
Checkpoint 3
Challenge
The problem is called fizz buzz, and has been used in job interviews, university entrance tests, and more for as long as I can remember. Your goal is to loop from 1 through 100, and for each number:
- If it’s a multiple of 3, print “Fizz”
- If it’s a multiple of 5, print “Buzz”
- If it’s a multiple of 3 and 5, print “FizzBuzz”
- Otherwise, just print the number.
Solution
for i in 1...100 {if i.isMultiple(of: 3) && i.isMultiple(of: 5){print("FizzBuzz")}else if i.isMultiple(of: 3) {print("Fizz")}else if i.isMultiple(of: 5) {print("Buzz")}else {print(i)}}