4.16 Exercise: Stars
So, this exercise is a very popular exercise for beginning programmers. So we have this function, display stars, with a parameter called rows. So when we call this function and pass 5, We get 5 rows. In each row, we have a star, and the number of stars in that row, depends on the row we are in. So in the first row we have one star, in the second row we have 2 stars, and so on. If you call this function passing 1, we get only one star, if we pass 2, we get 2 rows, if we pass 10, you get the point. So go ahead and do this exercise, when you're done, come back and continue looking at the correction. So here we have to start with a for loop, so we do a let row And we set it to 1, as long as the row is less than or equal to the number of rows, we want to increment the row. Now in each row, depending on the number of rows, we need to display one or more stars. So here I'm going to declare a variable, we're going to call it pattern, we set it to an empty string. Now, depending on the value of the line, we need to add one or more stars to this pattern. So here we need another for loop, so for let's call this i and set it to 0, as long as i is less than row, let's increment i and here we add a star to the pattern, so += star. So if you're on row 5, this loop will run 5 times, because we started from 0, and we're running it while i is less than row, so this will run 5 times, and each time we will add a star to our empty string. So we'll end up with 5 stars. Finally, when we're done, with this loop, we do a console. Pattern log, Now, at the top, I'll change this to 5, save the changes, and the algorithm works very well if you pass 1, you get 1 star if we pass 2, we get 2 stars. So what we have here is what we call a loop nest. So we have a loop inside another loop. And you can see this pattern in many algorithms.