0

I have to print a triangle formed of '#'.

This is my code:

function show(n){
  var text ="";
for(var i=1;i<=n;i++){
    for(var j=1;j<=i;j++){
        text+='#';

      }
     console.log(text);
    }

}
show(4);

For this input I get:

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

But I want to get:

#
##
###
####

What is wrong in my code? Thanks

3
  • 1
    You do not reset text inside the loop. So each line will be appended to the last one. Commented Jul 25, 2016 at 7:16
  • 2
    As an option, you can use for (var i = 1; i <= n; i++) { console.log('#'.repeat(i)); }. Commented Jul 25, 2016 at 7:17
  • @Tushar Very informative, Indeed. Commented Jul 25, 2016 at 7:23

3 Answers 3

4

Try to clear your text in the outer for loop,

for(var i=1;i<=n;i++){
    text = "";

Full code would be,

function show(n){
 var text;
 for(var i=1;i<=n;i++){
    text = "";
    for(var j=1;j<=i;j++){
        text+='#';
    }
    console.log(text);
 }
}
show(4);
Sign up to request clarification or add additional context in comments.

Comments

2

You don't need two loops for that. Just append one character in each iteration and print it out:

var text = "";

for(var i=0; i < n; i++){ 
 text += "#";
 console.log(text); 
}

//prints for n=8: 

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

Comments

0

You can do loop this way:

<div id="result"></div>
<script>
function show(n){
    var text = "";
    for(var i=1;i<=n;i++){
        for(var j=1;j<=i;j++){
          text+='#';
        }
        text+="<br/>";
        document.getElementById('result').innerHTML = text;
    }
}
show(4);
</script>

Your Output

Comments

Your Answer

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