Home > Mobile >  How do I create an infinite addition output loop in JS/node?
How do I create an infinite addition output loop in JS/node?

Time:11-22

I am new to JS. For fun I want to create an infinite loop that outputs the following way: 1 1=2, 2 2=4, 4 4=8, 8 8=16 and so on...This is what I have so far. I created a For loop to concise my theories/methods for practice, but I still can't get it to work properly.

for (let i = 0; i < 5; i  ) {
  num1 = i;
  sum = i * 2;
  answer = sum * 2;
  console.log(sum   "   "   sum   " = "   answer * i);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

At the moment you're just multiplying variables by two when really you want to take the result of adding two numbers together and use it in the next iteration.

Declare a step variable outside of the loop. On each iteration assign the the sum of two steps to an answer variable, log the result, and then assign answer to step.

let step = 1;

for (let i = 1; i < 10; i  ) {
  let answer = step   step;
  console.log(`${step}   ${step} = ${answer}`);
  step = answer;
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Additional documentation

  • Related