Mihir
Mihir

Reputation: 95

Undesired output in Javascript While loop

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
  ...

Upvotes: 1

Views: 62

Answers (3)

Ethan Fischer
Ethan Fischer

Reputation: 1489

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.

Upvotes: 0

Jai
Jai

Reputation: 74738

Concatenate the innerHTML and put it in loop:

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

} // <---end of while

Upvotes: 1

PRVS
PRVS

Reputation: 1690

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.

Upvotes: 2

Related Questions