-1

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;
}
Samurai
3,7295 gold badges29 silver badges41 bronze badges
asked Jun 11, 2015 at 3:27
0

4 Answers 4

2

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>

answered Jun 11, 2015 at 3:30
Sign up to request clarification or add additional context in comments.

Comments

1

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>

answered Jun 11, 2015 at 3:33

Comments

0

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);
answered Jun 11, 2015 at 4:14

Comments

0

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(', ');
}
answered Jun 11, 2015 at 6:04

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.