Home javascript JavaScript Add some code that raises the number 2 to the power...

# JavaScript Add some code that raises the number 2 to the power 10. Use a for loop.

Author

Date

Category

Just learning, here’s my sketch. What’s missing?

``````var num = 2;
var exp = 10;
var count = 2;
var result = num;
for (var count = 2; count & lt; = exp; count ++) {
console.log (count);
}
``````

The number 1024 should be displayed in the console.

Let’s first describe the algorithm. “2 to the power of 10” means that you need to multiply 10 twos. `2 * 2 * 2 ... * 2 `– & nbsp; two ten times, multiplication 9 times.

In order not to write a long sausage of multiplications, let’s do it in a loop, as requested.

Let there be a `result `variable that stores the current value of the multiplication. And inside the loop, which we will loop 9 times (how many times “multiplication”), we will multiply by 2:

``````for (blabblah) {
result = result * 2;
}
``````

This `result `will contain the desired result after nine times.

It remains to arrange the cycle. Inside there are three expressions:

1. Initial values.
2. Conditions to be met. As soon as they are violated – & nbsp; exit the loop.
3. Actions on every repeat.

Let’s do the counter `i `with the variable. Repeat 9 times, each time decreasing by 1. Spin until we reach zero:

``````for (i = 9; i & gt; 0; i = i-1)
``````

And finally, at the very beginning, you need to declare / give initial values ​​to all variables:

``````var i, result, exp = 10, num = 2;
``````

Next, please collect it yourself. Almost everything is here. Instead of a fixed value, use the `exp `variable in the loop.

``````function power (base, exp) {
var result = 1;
for (var i = 0; i & lt; exp; i ++)
{
result = result * base;
}
return (result);
}
console.log (power (2,10));
``````

``````var num = 2;
var exp = 10;
var result = 1;
var cnt = 1;
while (cnt & lt; = exp) {
result = result * num;
console.log (result)
cnt ++;
}
``````

``````function power (base, exponent) {
if (exponent == 0) {
return 1;
} else {
return base * power (base, exponent - 1)
}
}
console.log (power (2,10);
``````

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.