Follow

# Gaurav Patil Blog

Follow # Find the Power of a Number in Javascript

## We will discuss two methods to solve this problem using Javascript

Gaurav Patil
·Feb 16, 2023·

• Method 1: Without While Loop
• Method 2: With While Loop
• Conclusion

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` and `res2` variables without initializing them.

• step 6: Use the `Math.pow` method to calculate the result of `base` raised to the power of `expo1` and assign the result to `res1`.

• step 7: Use the `Math.pow` method to calculate the result of `base` raised to the power of `expo2` and assign the result to `res2`.

• step 8: Use `console.log` to output the value of `base` raised to the power of `expo1` in the format `base ^ expo1 = res1`.

• step 9: Use `console.log` to output the value of `base` raised to the power of `expo2` in the format `base ^ 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();
``````

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 of `base` and assign the result to `res`.

• step 7: Decrement the value of `expo` by 1.

• step 8: End the while loop.

• step 9: Use `console.log` to output the value of `res` 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();
``````

Result = 4