Day 8 NuCamp _ For Loops

Fun Exercise breakdown

Kenny Hin
4 min readJul 5, 2022

Star Staircase:

The finished product
Output

Line 1

For STARters, the product of the output is printing the stars variable multiple times. Stars is declared with a empty string — the for loops adds the stars in line 4

Line 2

One thing to note on Line 2 is it’s mainly used as a counter/parameter for the nested for loop on Line 3. Line 2 will continue to increment after stars are added on Line 4.

Line 3–4

The nested for loop continues to add “*” to the variable stars until the *end* range is reached, which in this loop is “i”, which continues to iterate for 4 loops — (end of for loop on line 2 is 5). NOTE: The for loop on Line 3 range resets to 0 after every loop.

Diving into the Loop

To keep track, I had to make a T chart.

Highly Recommend 5/5 stars (pun intended)

RUN

Like chart above, stars is currently an empty string so we can add stars for our star staircase.

Into the first for loop, i =0, and we know we will start at (0) with our end at (5), while incrementing by (1) at every loop.

Remember, i = 0

Into the nested for loop, where the range is currently (0 , 0 , 1). Since this loop ends at 0 ( the value of i ), no stars are added because the for loop never executes! Print statement still executes, but its an empty string.

Current T chart looks like this:

Congrats! First loop just executed. Now we increment Line 2 by 1.

So now i =1

Into the nested for loop, the current range is (0,1). — j can finally start, its current value is 0. It has not reached its end (1), it will execute Line 4 and finally add “*” to the variable star. After Line 4 is executed, Line 5 will print the single * into our terminal. This is how we look so far:

Now we jump back to line 2, now i = 2. This is where i realized Line 2 simply sets the End for Line 3.

Now when Line 3 runs, the range is (0,2) — Meaning the loop will run TWICE. Once when j= 0, and another when j = 1. ( Remember, 2 is the end). Once j = 2 is reached, no stars will be added and j will go back holding the value of 0 when the new loop starts.

I believe what gets confusing is when we re-start the entire loop, j is actually reset back to 0. While “i” will hold its value. When we run Line 2 again, it will set the END to 3. But when we jump back into Line 3 with the nested loop, j = 0. So right now, this is our current state:

After this iteration executes, you’ll notice a pattern. The current value of i will be equivalent to the stars added.

Mission complete.

--

--