1

I want to print something like:

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

My code is:

<html>
<head>
    <title>Learning Javascript</title>
</head>
<body>


<script type="text/javascript">
    for (var i = 1; i <= 7; i++) {
        for ( var j = 1 ; j <= i ; j++ )
        {
            console.log("#");
        }
    }
</script>
</body>
</html>

It gives only a single #:

#

Why am I not getting expected output in console log? I have tried both chrome and firebug.

2
  • it'll give a single # 28 times, is that right Commented Nov 13, 2015 at 2:56
  • Yes.... I am getting something like that. Commented Nov 13, 2015 at 3:08

2 Answers 2

7

Actually, I believe you're getting 28 of them, but the console "merges" them into one.

enter image description here

In any event, your code is printing # on a separate line each time. You want to concatenate j #s and print that in the outer for loop.

Alternatively, you can do this:

for (var i = 1; i <= 7; i++) {
    console.log("#".repeat(i));
}
Sign up to request clarification or add additional context in comments.

Comments

3

In console same value will be counted instead of printing separately

If you wanna to to print separately then concat as string then print

Try like this

for (var i = 1; i <= 7; i++) {
    var str="";
    for (var j = 1; j <= i; j++) {
       str+="#"
    }
    console.log(str);
}

JSFIDDLE

2 Comments

I am assuming ur missing a ";" after str+="#".. shouldn't it be str+="#";.. not that it matters, even without it; still works perfect..
Thanks for pointing . it's just a typo . it's not a big deal in javascript though @GMB

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.