> For the complete documentation index, see [llms.txt](https://ios-course.cornellappdev.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ios-course.cornellappdev.com/resources/textbook/swift-basics/loops.md).

# Loops

When we want to repeat a code a certain number of times in Swift, we can either copy and paste the code or even better, we can use **loops**. There are two main loops in Swift: a **for loop** and a **while loop**.

### Looping over a fixed number of times

Let’s say we wanted to print out the numbers `1..10`. In Swift, we can use the **closed range operator** (`...`) which is three periods in a row.

```swift
for i in 1...10 {
    print(i)
}
```

<figure><img src="/files/LgEMZNcHSOBcJQBzKwuC" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**In a couple of these examples, we used `i` as the loop variable. This is a common convention used by programmers, but we can name it whatever we want.**
{% endhint %}

The variable `i` is known as a **loop variable** which is a variable that lives within the scope and lifetime of the loop. For every iteration, the value of `i` will change. Now, what if we didn’t need to use `i` and just wanted to print `"Hello Vin and Richie"` 10 times? We could still use `for i in 1...10`; however, it would be better to use an underscore (`_`) instead.

```swift
for _ in 1...10 {
    print("Hello Vin and Richie")
}
```

Why is `...` called a *closed range operator*? Well, that’s because there is also an **open range operator** (`..<`). The difference between these two is that the *closed range operator* is inclusive whereas the ***open range operator*** is not. The following code will only be executed 9 times. It goes up to but not including 10.

```swift
for _ in 1..<10 {
    print("Hello Vin and Richie")
}
```

<figure><img src="/files/rHwVerFXzMj23z4qMVwa" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**The print statement is very useful for debugging purposes. The user will not be seeing the output when using the app. It is only for the programmer.**
{% endhint %}

### Looping over arrays

Swift provides a nice way to loop over the elements of an array using the **for-in** loop.

```swift
var staff = ["Vin", "Richie", "Tiffany", "Jennifer", "Antoinette", "Elvis"]
for person in staff {
    print(person)
}
```

In this code, the loop variable is `person`. For every iteration of this loop, the value of `person` will be the value of every element inside of the array `staff`, in order.

<figure><img src="/files/D92PzoAKUI5Sb65Mvvnq" alt=""><figcaption></figcaption></figure>

Instead of looping over the ***element*** of the array, we could have looped over the ***indices*** of the array. The following code is equivalent:

```swift
var staff = ["Vin", "Richie", "Tiffany", "Jennifer", "Antoinette", "Elvis"]
for i in 0..<staff.count {
    print(staff[i])
}
```

<figure><img src="/files/3mwPzxpzodKNyZO1Oxoz" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**We can also nest for loops inside of other for loops!**
{% endhint %}

### While Loops

If we don’t know exactly how many times to repeat a block of code, but do know that we want to repeat it while a condition is true, then we can use a **while loop**.

```swift
var i = 0
while i < 10 {
    print(i)
    i += 1
}
```

The above code will print out the value of `i` and increment the value of `i` by 1 ***while*** `i < 10` evaluates to `true`.

<figure><img src="/files/plUJjRAeMbgyeHUujxgq" alt=""><figcaption></figcaption></figure>

However, be very careful when using while loops because we can create an infinite loop. In the code below, the value of `i` never changes and will always be less than 10. In this case, there will be an infinite loop:

```swift
var i = 0
while i < 10 {
    print(i)
    // i += 1 commented out
}
```

{% hint style="info" %}
**We can use `break` or `continue` to stop/continue the loop but we it is not recommended.**
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ios-course.cornellappdev.com/resources/textbook/swift-basics/loops.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
