1

I get output of below code as n = 3, x = 6 but I require output as

n = 1, x = 1
n = 2, x = 3
n = 3, x = 6

Can some one help me what else should be added in code?

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>

    function myFunction() {
        var n = 0;
        var x = 0;
        while (n < 3) {
            n++;
            x += n;
        }
        document.getElementById("demo").innerHTML = "n = " + n + ", " + "x = " + x;
    }

</script>

</body>
</html>

@Jai Below example is similar,

function myFunction() {
    var text = "";
    var i = 0;
    while (i < 10) {
        text += "<br>The number is " + i;
        i++;
    }
    document.getElementById("demo").innerHTML = text;
}

output is

The number is 0  
 The number is 1
  ...
1
  • If any response help you, you should accept the answer, meta.stackexchange.com/questions/5234/… . ;) I see that another questions that you made, you don't accept any answer, and maybe you are new here. Commented Feb 16, 2016 at 9:26

3 Answers 3

2
function myFunction() {
    var n = 0;
    var x = 0;
    while (n < 3) {
        n++;
        x += n;

    document.getElementById("demo").innerHTML += 
    "n = " + n + ", " + "x = " + x;
    }

}

You have to "add" to inner html. So, put "+=" and inside the loop.

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

Comments

1

Concatenate the innerHTML and put it in loop:

document.getElementById("demo").innerHTML += 
"n = " + n + ", " + "x = " + x;

} // <---end of while

4 Comments

can you help me understand why are we concatenating innerHTML because other examples I went through had document.getElementById outside while loop. Can I paste the link to example here?
@Mihir its because innerHTML replaces all the existing contents of that element. But adding new content with existing contents should be done with +=.
I have added another example in my first post but concatenation is not used there. am not able to relate whether both scenarios referred are different?
That is another way via defining a variable text to store the result and when loop exits all the appended values set via innerHTML. and in this case you don't have to put innerHTML inside of loop.
0

Your code executes the while loop 3 times, updating the values of n and x each time. But because you write the output outside of the while loop, you only see the last values. You need to put a line that displays your variables INSIDE the while loop.

Comments

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.