Understanding calling a function within a loop

Understanding calling a function within a loop
0
#1

I was hoping some of you could help me in understanding a snippet of code I have been doing some practice with. In another one of my resources to learn code, we are using functions and loops to print out a triangle shape of the # symbol. The code looks like this.

function createTriangle (height) {

for (var i = 1; i <= height; i++) {
var row = ‘’;
for (var j = 1; j <= i; j++) {
row += ‘#’;
}
console.log(row);
}
}
createTriangle(7)

Once executed, it then prints out one of the first line, 2 on the second, so on until 7. From my understanding, we are using a function and passing a number value of 7 to call that function towards the end. The loops are used to loop through the code to print out the triangle, but that is the part im hazy on. And the reason for two loops.

Just trying to seek a little clarification. If anyone has a moment to help me understand this, would really appreciate it.

Thanks alot!

0 Likes

#2

See the same code refactored with comments explaining what is going on.

``````function createTriangle (height) {
for (var i = 1; i <= height; i++) { // outer loop creates the rows to hold the #s with i representing the applicable row number
var row = ''; // each row string should start blank to build upon
for (var j = 1; j <= i; j++) { // inner loop variable j creates i #s
row += '#'; // row grows by one additional # each iteration
}
console.log(row); // display the current row string
}
}
createTriangle(7)
``````

Running the above code displays the following in the console:

``````#
##
###
####
#####
######
#######
``````

Below uses the same logic but renames the variables to make it clear what each represents

``````function createTriangle (height) {
for (var rowNumber = 1; rowNumber <= height; rowNumber++) {
var rowStr = '';
for (var column = 1; column <= rowNumber; column++) {
rowStr += '#';
}
console.log(rowStr);
}
}
``````

See if this helps you understand what is going on.

0 Likes

#3

As always thank you very much randell

0 Likes