Christmas tree in Javascript using stars

zbierek Source

I have this loop problem, I really don't understand why my code doesn't work, I've even draw this on paper and for my logic it looks good but it's not working, please help me.

function drawTree(h) {
  for(var i=0; i<=h; i++){
    var star = '';
    for(var k=0; k<=1; k++){
      star += "  ";
    };
    for(var j=0; j<=i; j++) {
        star += "*";
    };
  };
    console.log(star);
};

drawTree(5);

javascript

Answers

answered 5 months ago Thomas Edwards #1

You’re re-setting it each line, but printing it only at the end.

Move console.log(star); to the end of the first loop.

answered 5 months ago Mani #2

You have to place the console.log statement inside first for loop. That should give a half tree. If you want correct tree, then pre-pend spaces before star. Calculate the center of the number of rows and add spaces before it.

Hope this not an assignment problem.

function drawTree(h) {
  for(var i=0; i<=h; i++){
    var star = '';
    for(var k=0; k<=1; k++){
      star += "  ";
    };
    for(var j=0; j<=i; j++) {
        star += "*";
    };
    console.log(star);
  };

};

drawTree(5);

answered 5 months ago ASDFGerte #3

See comments in the code for changes.

function drawTree(h) {
  for(var i=0; i<=h; i++){
    var star = '';
    //Changed to start high then decrease
    for(var k = 1; k <= h - i; k++){
      //shortened to one space
      star += " ";
    };
    for(var j=0; j<=i; j++) {
        //Added space so there is an odd number
        //of symbols and the star above fits
        //the space
        star += " *";
    };
    //Moved into the loop
    console.log(star);
  };
};

drawTree(5);

Note that the code can be substantially shortened using String.prototype.repeat:

function drawTree(h) {
  for (var i = 0; i <= h; i++){
    console.log(" ".repeat(h - i) + " *".repeat(i + 1));
  };
};

drawTree(5);

Also note that your example produces a base line with six stars for a call of drawTree(5). I am unsure whether that is intended. The code above reproduces said behavior, editing it to show a line less should not be too hard.

answered 5 months ago vicky patel #4

function drawTree(h){
for (var i = 0; i < h; i++) {
var star = ''; 
var space = (h - i);
if (i == 0){
star += ' '.repeat(space + 1) + '\n';
}
star += ' '.repeat(space + 1);
var zero = 2 * i + 1;
star += '*'.repeat(zero);
console.log(star);
}
}
drawTree(5);

comments powered by Disqus