Nick Dorsett
Nick Dorsett

Reputation: 1

Javascript loop. What am I doing wrong?

Trying to make a loop that outputs 2 to the power of 0-31. So far I only have it giving me 2 to the power of 31. What am I doing wrong?

function findPower()
{
    var answer=0;

    for(var i=0;i<=31;i++)
    {
        answer=Math.pow(2,i);
    }

    document.getElementById("output").innerHTML=answer;
}

Upvotes: -1

Views: 102

Answers (4)

Peter Pan
Peter Pan

Reputation: 24128

Maybe it's better and faster.

function findPower() {
  var answer = [];
  var pow = 1;
  answer.push(pow);
  for (var i = 1; i <= 31; i++) {
    pow *= 2;
    answer.push(pow);
  }
  document.getElementById("output").innerHTML = answer.join(', ');
}

Upvotes: 0

user1636522
user1636522

Reputation:

If I get you right you want to calculate a sum of powers of 2:

for (var i = 0; i <= 31; i++) {
    answer += Math.pow(2, i);
}

Notice the "+" sign. Writing:

answer += Math.pow(2, i);

Is the same as writing:

answer = answer + Math.pow(2, i);

Upvotes: 0

user786
user786

Reputation: 4364

You statement inside loop "document.getElementById("output").innerHTML=answer;" is overriding previous value so you are getting the last value. So what I did is to concatinate the values instead of overriding previous values

it should like following

   function findPower() {
     var answer = 0;

     for (var i = 0; i <= 31; i++) {
       answer = Math.pow(2, i);
       document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + "," + answer
     }


   }
<body onload="return findPower();">
</body>
<span id="output"></span>

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Because in the loop in each iteration you are overriding the value of answer, so at the end it will have the value of last iteration only.

If you want to iterate the value of each number, then an easy solution is to push them to an array and after the loop join them to create the answer string as below

function findPower() {
    var answer = [];

    for (var i = 0; i <= 31; i++) {
        answer.push(Math.pow(2, i));
    }

    document.getElementById("output").innerHTML = answer.join(', ');
}

function findPower() {
  var answer = [];

  for (var i = 0; i <= 31; i++) {
    answer.push(Math.pow(2, i));
  }

  document.getElementById("output").innerHTML = answer.join(', ');
}

findPower();
<div id="output"></div>

Upvotes: 2

Related Questions