Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first part of this basic loop exercise right?

Tags:

javascript

I am learning Javascript from the book Eloquent Javascript by Marijn Haverbeke, there is exercise at the end of second chapter(Program Structure). Write a loop that makes seven calls to console.log to output the following triangle:

#
##
###
####
#####
######
#######

I tried to solve it like using a for loop.

var hash = "#";

for(counter = 0; counter < 8; counter ++)
{

   hash = hash + "#";

   console.log(hash);

}

The problem is it's showing not showing the first line of the required output, how do I get that?

I would greatly appreciate any solution especially if it comes with a little explanation.

like image 252
Mohil Avatar asked Feb 19 '16 20:02

Mohil


People also ask

What are the 3 parts of a for loop?

Similar to a While loop, a For loop consists of three parts: the keyword For that starts the loop, the condition being tested, and the EndFor keyword that terminates the loop.

What is the order in which for loop works?

So first the condition is checked, then the loop body is executed, then the increment.


1 Answers

Nice job since you're just starting.

You almost got it. Just declare the variable as an empty string.

// this is the line that needs to be changed
var hash = '';

for(....) {
  hash += "#";
  console.log(hash);
}

This way as you add to the "hash" variable inside the loop, it doesn't have that extra "#" from variable declaration.

like image 160
gimbel0893 Avatar answered Sep 23 '22 05:09

gimbel0893