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;
}
4 Answers 4
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>
Comments
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>
Comments
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);
Comments
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(', ');
}