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.
Answer 1, authority 100%
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:
- Initial values.
- Conditions to be met. As soon as they are violated – & nbsp; exit the loop.
- 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.
Answer 2, authority 40%
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));
Answer 3
var num = 2;
var exp = 10;
var result = 1;
var cnt = 1;
while (cnt & lt; = exp) {
result = result * num;
console.log (result)
cnt ++;
}
Answer 4
function power (base, exponent) {
if (exponent == 0) {
return 1;
} else {
return base * power (base, exponent - 1)
}
}
console.log (power (2,10);