Algorithm


  1. Function Definition:

  2. Define a recursive function power that takes two parameters: base (the base number) and exponent (the power to which the base is raised).

    Base Case:

    Check if exponent is equal to 0.

  3. If true, return 1 (any number raised to the power of 0 is 1).

    Recursive Case:

  4. If exponent is not equal to 0:Return the result.

  5. Multiply the base by the result of the recursive call to power with parameters base and exponent - 1.

    Input:

    Get user input for the base and exponent.

    Calculate Power:

    Call the power function with the user-input base and exponent.

    Output:

    Display the result of the power calculation.

The C++ program provided earlier in the conversation follows this algorithm. This algorithm recursively calculates the power by reducing the exponent in each recursive call until it reaches the base case where the exponent is 0.

 

Code Examples

#1 Code Example- C++ Programing Compute Power Manually

Code - C++ Programming

#include <iostream>
using namespace std;

int main() 
{
    int exponent;
    float base, result = 1;

    cout << "Enter base and exponent respectively:  ";
    cin >> base >> exponent;

    cout << base << "^" << exponent << " = ";

    while (exponent != 0) {
        result *= base;
        --exponent;
    }

    cout << result;
    
    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter base and exponent respectively: 3.4
5
3.4^5 = 454.354

#2 Code Example- C++ Programing Compute power using pow() Function

Code - C++ Programming

#include <iostream>
#include <cmath>

using namespace std;

int main() 
{
    float base, exponent, result;

    cout << "Enter base and exponent respectively:  ";
    cin >> base >> exponent;

    result = pow(base, exponent);

    cout << base << "^" << exponent << " = " << result;
    
    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter base and exponent respectively: 2.3
4.5
2.3^4.5 = 42.44
Advertisements

Demonstration


C++ Programing Example to Calculate Power of a Number-DevsEnv