Search code examples
javascriptwhile-looppow

Is it possible to display the row of 2 in the power of 1,2...10 (the biggest) using while loop with Math.pow?


Here is my code that doesnt work. It seems to me that it has to but when I use console (in inspect section in the browser) nothing happens, it doesnt find any bug.

I`d be very thankful if you explain me where is the mistake(-s)

var counter = 0;
var result = Math.pow (2, counter);
    while (result < Math.pow (2, 10)) {
    console.log(result);
    counter = counter + 1;
    }

Solution

  • As juvian stated in the comments, you're updating the variable "counter" in your while loop, but you also need to update "result" in every loop as well. Here's a revised version of your code with an explanation.

    // Counter starts at zero
    var counter = 0;
    
    /*
        Result needs to be initialized to check the
        initial condition.
    
        Alternatively, we could have changed the
        condition of the while loop to something like:
        while (counter <= 10) { ... }
    
        (this would be technically faster because
         you're not re-computing Math.pow(2,10))
    */
    var result = 0;
    
    // We perform the code in here until the condition is false
    while (result < Math.pow (2, 10)) {
        // First, we raise 2 to the power of counter (0 the first time)
        var result = Math.pow (2, counter);
        // Print the result
        console.log(result);
        // Now increment the counter
        // (this will change what the first line of the loop does)
        counter = counter + 1;
    }