Find the Power of a Number in Javascript
We will discuss two methods to solve this problem using Javascript
Hi everyone today we Find the Power of a Number in Javascript. let's discuss how to solve this problem statement. if you want to check out yesterday's problem click here.
Given two integers as the number and power inputs, the objective is to raise the number input to the power input and print the value.
Method 1: Without While Loop
Method 2: With While Loop
Method 1: Without While Loop
Algorithm
step 1: Define the
main
function.step 2: Declare and initialize the
base
variable to 1.5.step 3: Declare and initialize the
expo1
variable to 2.5.step 4: Declare and initialize the
expo2
variable to -2.5.step 5: Declare the
res1
andres2
variables without initializing them.step 6: Use the
Math.pow
method to calculate the result ofbase
raised to the power ofexpo1
and assign the result tores1
.step 7: Use the
Math.pow
method to calculate the result ofbase
raised to the power ofexpo2
and assign the result tores2
.step 8: Use
console.log
to output the value ofbase
raised to the power ofexpo1
in the formatbase ^ expo1 = res1
.step 9: Use
console.log
to output the value ofbase
raised to the power ofexpo2
in the formatbase ^ expo2 = res2
.step 10: Call the
main
function to execute the code.
Javascript Code
function main() {
let base = 1.5;
let expo1 = 2.5;
let expo2 = -2.5;
let res1, res2;
// calculates the power
res1 = Math.pow(base, expo1);
res2 = Math.pow(base, expo2);
console.log(base + " ^ " + expo1 + " = " + res1);
console.log(base + " ^ " + expo2 + " = " + res2);
}
main();
Output
2 ^ 2 = 4
2 ^ -2 = 0.25
Method 2: With While Loop
Algorithm
step 1: Define the
main
function.step 2: Declare and initialize the
base
variable to 1.5.step 3: Declare and initialize the
expo
variable to 2.step 4: Declare and initialize the
res
variable to 1.0.step 5: Enter a while loop that runs while
expo
is not equal to 0.step 6: Multiply the value of
res
by the value ofbase
and assign the result tores
.step 7: Decrement the value of
expo
by 1.step 8: End the while loop.
step 9: Use
console.log
to output the value ofres
in the format"Result = " + res
.step 10:Call the
main
function to execute the code.
Javascript Code
function main() {
let base = 2;
// Works only when exponent is positive integer
let expo = 2;
let res = 1.0;
while (expo !== 0) {
res *= base;
expo--;
}
console.log("Result = " + res);
}
main();
Output
Result = 4
Conclusion
So this article we solved the problem statement using javascript language. I hope you found this article helpful for your web development journey.
If you fill this article informative please like this article, if you have any suggestions please comment on this article, share it on social media and follow me on
Hashnode - Gaurav Patil
Twitter - @GauravYPatil