1

I'm looking for feedback/insight on using console.log instead of document.write to solve the looping triangle with a space in the CS50 Mario style problem.

Triangle loop - CS50 mario style

var str = "#";
var height = 8;
for (var i = 0; i < height; i++) {
  for (var j = 0; j < height-i-1; j++) {
    document.write("_");
  }
  {
    for (var k = 0; k < i + 2; k++) {
    document.write(str);
    }
  document.write("<br />");
  }
}

//
_______##
______###
_____####
____#####
___######
__#######
_########
#########

The document.write(“_”) is because the DOM trims any white space so (“ “) won't work - took me ages to figure that out.

I can’t get the triangle to come out right aligned using console.log() instead of document.write - any thoughts?

Cheers - I'm a huge SOF fan for learning.

3
  • Please keep your question focused on one specific issue. What code piece isn't working, and how isn't it working? Do you get an unexpected output, an exception, ..? Please edit these informations in your question. Commented Jan 7, 2016 at 2:08
  • 2
    codereview is a forum to invite feedback on how to improve working code and may be a better place to post your question than here. Commented Jan 7, 2016 at 2:09
  • "I can't get" --- is not a problem description. Commented Jan 10, 2016 at 23:46

1 Answer 1

1

The reason console.log is not working for you is because console.log auto changes lines. So if you want to use console.log version, switch to the below version:

var str = "#";
var height = 8;
for (var i = 0; i < height; i++) 
{
  var line = "";
  for (var j = 0; j < height-i-1; j++) {
    line += " ";
  }
  for (var k = 0; k < i + 2; k++) {
    line += str;
  }
  console.log(line);
}

Tested working with node.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much Lance, that makes sense - I really appreciate you taking the time to explain your worked answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.