Learn Courses My Dashboard

Explanation for loops (for a beginner)

Hello, I’m a complete beginner learning swift. Everything’s clear to me until I get to loops. I asked this question in the YouTube comments as well (but I noticed he asked others with questions to go here). Anyway, I was watching Chris’s video

The video itself was pretty clear. But it used only simple loops. I was doing his worksheet. It was asking to create a shape that looks like this.
x
xx
xxx
xxxx
xxxxx
xxxxxx
xxxxxxx

But the shape must be created using code. The worksheet tells me what to DO, as in what to type and what loops to create, but I don’t understand how it does it and I can’t follow the code. As it turns out, here’s the code he used to do this…
var drawPixel:String = “*”

var height:Int = 5

var tempRow:String = “”

for columnPixel in 1…height {

tempRow = “”

for _ in 1…columnPixel{

tempRow += drawPixel

}

print(tempRow)

}

Sorry about the weird formatting for the code. Anyway, I don’t really understand it at all. What does using a nested loop do? I really can’t follow it and wouldn’t be able to come up with it without the answer key. I also don’t know what the tempRow variable set to nothing does in the loop. In other words, I’m completely confused looking at this.

Clarification: var drawPixel:String = “x” not “*” if that confused anyone.

Hey @tylvaughan! Welcome to the code crew forums!

You can format your code by wrapping it with three backticks:
```
code here
```

And with that, lemme format the code for you and give you some explanation on how it works, and how I would visualize/understand it.

var drawPixel: String = "x"
var height: Int = 5
var tempRow: String = ""

for columnPixel in 1...height {
    tempRow = ""
    for _ in 1...columnPixel {
        tempRow += drawPixel
    }
    print(tempRow)
}

This code will print an output:

x
xx
xxx
xxxx
xxxxx

Understanding Loops

When I was learning loops, what worked for me is tracing the code and writing the output into a piece of paper. I did this so I would clearly understand what happens each step of the loop.

If you find nested loops difficult to trace, you can take a step back and watch what happens in a single, non-nested loop.

Single non-nested loop

Now, let’s rewrite the code without the nested loop:

height = 3

for columnPixel in 1...height {
    tempRow = "x"
    print(tempRow)
}

Let’s break this code down so we can have a better understanding on how the loop works.

for columnPixel in 1...height means you start the loop with columnPixel = 1 and the loop would continue until columnPixel = height. If we assume that height = 3, then the loop would work 3 times.

The three dots ... is a range operator, so 1...height can be also read as 1 to 3, if height = 3.

columnPixel = 1 (prints an x into the console)
columnPixel = 2 (prints an x into the console)
columnPixel = 3 (prints an x into the console)

The code above would show an output:

x
x
x

In the code with the nested loop, the outer loop for columnPixel in 1...height is the loop that is responsible for printing rows.

The inner loop for _ in 1...columnPixel is the loop that is responsible for printing columns.

Nested Loops

Going back to the nested loop above,

height = 3

for columnPixel in 1...height {
    tempRow = ""
    for _ in 1...columnPixel {
        tempRow += drawPixel
    }
    print(tempRow)
}

We can trace this code every step of the way.

Let’s start with the outer loop: for columnPixel in 1...height. If height = 3, then this loop will run 3 times.
Initially, columnPixel = 1, then it will increment (increase in value) until columnPixel = 3.

columnPixel = 1
columnPixel = 2
columnPixel = 3

For each iteration of the outer loop with columnPixel, we’ll trace the code inside the loop and check what happens each step of the way:

Let’s start with columnPixel = 1

columnPixel = 1

    tempRow = ""
    for _ in 1...columnPixel {
        tempRow += drawPixel
    }
    print(tempRow)

The inner loop can be rewritten as: for _ in 1...columnPixel, since columnPixel = 1, we get: for _ in 1...1, which is a loop that starts with 1, and ends with 1. The underscore _ means you won’t be assigning a variable name to the loop counter, and you’ll just go ahead with the loop count. Since the loop starts with 1 and ends with 1, the loop will only run a single time. If this sounds confusing, it’s alright, you can send a reply so we can simplify it further.

The code inside the loop will run a single time so that means: tempRow += drawPixel will run a single time.

+= is a shorthand syntax for tempRow = tempRow + drawPixel, and since both are String types, you get tempRow = "" + "x", thereby tempRow = "x"

The succeeding print statement should show a single x in the console.

Output so far:

x

columnPixel = 2

    tempRow = ""
    for _ in 1...columnPixel {
        tempRow += drawPixel
    }
    print(tempRow)

The inner loop can be rewritten as: for _ in 1...2 since columnPixel = 2 at this state of the loop.
This would mean that the inner loop would execute 2 times and would thereby execute tempRow += drawPixel twice.

In the first run, tempRow = "" is currently an empty string, and adding the drawPixel = "x" to it would simply concatenate a single "x".

On the second run, tempRow = "x", and adding another drawPixel = "x" would make it tempRow = "xx". That’s what tempRow += drawPixel means, it simply appends the drawPixel string into it.

So the output at this point of the loop would be:

x
xx

columnPixel = 3

    tempRow = ""
    for _ in 1...columnPixel {
        tempRow += drawPixel
    }
    print(tempRow)

We are now at the final outer loop (since height = 3).

We can rewrite the inner loop as: for _ in 1...3, since columnPixel = 3. This would mean that the inner loop would execute 3 times, and would append drawPixel = "x" into tempRow 3 times, making it:
tempRow = "xxx".

The output to the console would be as follows:

x
xx
xxx

I hope that I have somehow made it clear? If not you can go ahead and ask which part made you lost, and I’ll try to explain it the best I can.

Thanks so much for this @inaki.
I am understanding it now I think. I guess I just have one more question, why did we have to redefine tempRow in the outer loop? I’m getting the nested now but the tempRow is confusing me. If we only have it in the loop it should reset to zero each iteration. But we also have it outside the loop. Can you explain how the tempRow variable works?

Thanks for this answer! I understand the nested MUCH better now, and I’ll refer to it in the future!

1 Like

Hey @tylvaughan!

Having tempRow = "" at the start of the outer loop makes sure that the tempRow variable resets to an empty string when the outer loop starts.

Without adding it, tempRow will not reset and will just append drawPixels in the inner loop.

output:

x
xxx
xxxxxx

// breakdown:
x (tempRow initially being "" and having to append a single "x")
xxx (tempRow having a current value of "x" and having to append two "x"s)
xxxxxx (tempRow having a current value of "xxx" and having to append three "x"s)

When reading loops, you need to start from the top again, and having tempRow = "" will tell the outer loop to start with tempRow as an empty string before doing the inner loop which would append drawPixel = "x" a number of times.

so after print(tempRow), you need to read the loop from the top again, so having tempRow = "" is necessary to reset it to an empty string.

var drawPixel: String = "x"
var height: Int = 5
var tempRow: String = ""

for columnPixel in 1...height {
    tempRow = ""
    for _ in 1...columnPixel {
        tempRow += drawPixel
    }
    print(tempRow)
}

output:

x
xx
xxx

breakdown:
x (tempRow initially an empty "", and having to append a single "x")
xx (tempRow being reset as "", and having to append "x" twice)
xxx (tempRow being reset as "", and having to append "x" three times)

Thanks for this @inaki!
I’m getting it now.
Also I realize I can declare tempRow inside the outer loop instead of before it and it’ll work no problem. Thanks so much for your time, that was very clear.

1 Like