user3677169
user3677169

Reputation:

Javascript print triangle doesn't work as expected

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

Upvotes: 0

Views: 92

Answers (3)

Rahul K
Rahul K

Reputation: 413

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

Upvotes: 0

eol
eol

Reputation: 24555

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: 

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

Upvotes: 2

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

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);

Upvotes: 4

Related Questions