Reputation:
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
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>
Upvotes: 0
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
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