# W1154 For Loop

## Prerequisites[edit]

## Introduction[edit]

The **for loop** is a construct which enables us to execute a segment of code a *defined number* of times. It is thus the most appropriate choice when we know in advance how to calculate the number of iterations prior to beginning the loop. While this construct is not strictly necessary, it provides **syntactic sugar** by clarifying intent.

## For Loops[edit]

**for loops** execute for a defined count of iterations, as such, the *test condition* is implied within the definition. Through each iteration, a *loop control variable* is adjusted toward its final goal. When that goal is reached, the loop exits.

Both **while** and **repeat-while** loops require the *explicit definition* of a **loop control variable** which must be *explicitly incremented* (or otherwise adjusted) and *explicitly checked* each time through the loop to determine if the loop has completed. In contrast, a **for loop** handles this work for us *implicitly* by defining the loop control variable, incrementing (or otherwise adjusting) it automatically, and checking for the completion condition.

**The actual implementation is identical to that of a while loop.**

## Intervals[edit]

Assume two numbers, **a** and **b**, such that **b > a**. An **interval** is the set of numbers lying between these two numbers. Both **a** and **b** are the endpoints of the interval, the **lower bound** and the **upper bound** respectively. An **open interval** does not include either of the endpoints, a **half-open interval** include just one of its endpoints, while a **closed interval** includes both of its endpoints.

### Interval Notation[edit]

Notation | Interpretation | Description |
---|---|---|

(a, b) | a < x < b | An open interval; both endpoints are excluded. |

(a, b] | a < x ≤ b | A half-open interval; the lower bound is excluded. |

[a, b) | a ≤ x < b | A half-open interval; the upper bound is excluded. |

[a, b] | a ≤ x ≤ b | A closed interval; both endpoints are included. |

### Interval Classifications[edit]

An **empty interval** has no elements. Examples include:

- (b, a), (b, a], [b, a), [b, a]
- (a, a), (a, a], [a, a)

A **degenerate interval** has a single element. An example is:

- [a, a]

## Swift For Loops[edit]

Because iterating over a discrete interval is very common, Swift supports several different ways of implementing **for loops**.

### Swift Ranges[edit]

A range in Swift represents either a closed interval or a half-open interval. In both cases, one may iterate of the range.

#### ClosedRange[edit]

A **ClosedRange** includes both the lower bound and the upper bound. It's written using **...** between the lower and upper bounds. For example, the equivalent of [4, 7] is:

```
4 ... 7
```

An example of a loop using a ClosedRange is:

```
for x in lowerBound...upperBound {
print(x);
}
```

#### Range[edit]

A **Range** includes the lower bound but excludes the upper bound. It's written using **..<** between the lower and upper bounds. For example, the equivalent of [4, 7) is:

```
4 ..< 7
```

An example of a loop using a Range is:

```
for x in lowerBound..<upperBound {
print(x);
}
```

### Swift Strides[edit]

A **stride** in Swift represents either a sequence based upon a closed interval or a half-open interval.

#### Closed Stride[edit]

A **closed stride** includes the lower bound and *may* include the upper bound, stepping as specified. It uses the keyword **through** for the upper bound and is written as *stride(from:4, through:7, by:1)*.

An example of a loop using a closed stride is:

```
for x in stride(from:lowerBound, through:upperBound, by:1) {
print(x);
}
```

#### Half-Open Stride[edit]

A **half-open stride** includes the lower bound but excludes the upper bound, stepping as specified. It uses the keyword **to** for the upper bound and is written as *stride(from:4, to:7, by:1)*.

An example of a loop using a half-open stride is:

```
for x in stride(from:lowerBound, to:upperBound, by:1) {
print(x)
}
```

#### Stride By[edit]

Strides do not necessarily have to increment **by** 1; **by** can be any arbitrary value. A positive stride iterates upward; a negative stride iterates downward. One advantage of strides is that they may use floating point values.

## The Special Meaning of "_", or I Don't Care[edit]

Sometimes, we don't care about the value of a variable. For example, there are occasions where we want to execute something a certain number of times but we don't need to keep track of the specific iteration. The `_`

(underscore) character is intended for this purpose.

For example, if we want to print "Hello, World!" exactly one hundred times, we could type the following:

```
for _ in 1 ... 100 {
print("Hello, World!")
}
```

## Key Concepts[edit]

- The
**for loop**is a construct which enables us to execute a segment of code a*defined number*of times.- Both while and repeat-while loops require the
*explicit definition*of a loop control variable which must be*explicitly adjusted*and*explicitly checked*each time through the loop. In contrast, a for loop handles this work*implicitly*. - The actual implementation is identical to that of a while loop.

- Both while and repeat-while loops require the
**Intervals**: Assume two numbers, a and b, such that b > a. An**interval**is the set of numbers lying between these two numbers.- Both a and b are the endpoints of the interval, the
**lower bound**and the**upper bound**respectively. - An
**open interval**does not include either of the endpoints - A
**half-open interval**include just one of its endpoints - A
**closed interval**includes both of its endpoints - An
**empty interval**has no elements - A
**degenerate interval**has a single element

- Both a and b are the endpoints of the interval, the
- Swift defines two range types:
- A
**ClosedRange**includes both the lower bound and the upper bound and is written using**...** - A
**Range**include the lower bound but excludes the upper bound and is written using**..<** - A
*half-open stride*includes the lower bound and*may*include the upper bound and is written using**stride(from:a, to:b, by:s)** - A
*closed stride*includes the lower bound and*may*include the upper bound and is written using**stride(from:a, through:b, by:s)**

- A

Coming Soon | |

M1154-20 requires understanding of functions described in W1205. Therefore, that unit should be moved earlier and then M1154-20 into that unit. |

## Exercises[edit]

- M1154-10 Complete Merlin Mission Manager Mission M1154-10.
- M1154-20 Complete Merlin Mission Manager Mission M1154-20.
- X1154 Using Draw.IO create a single XML file named "Flowcharts.drawio" with one page for each flowchart below. Create a new subdirectory, J1154, in your Journals directory. Upload the file to the directory via SFTP. Be sure to push the file to your GitHub repository. When done, tag the repository as J1154.Final.
- Finding the greatest number of three
- Finding the GCD of two numbers using Euclid's Algorithm
- Determining whether or not a number is prime

## References[edit]

- Range (Swift Documentation)
- ClosedRange (Swift Documentation)
- Half-Open Stride (Swift Documentation)
- Closed Stride (Swift Documentation)
- Interval (Wikipedia)