Algorithm
-
Function Definition:
-
Define a recursive function
power
that takes two parameters:base
(the base number) andexponent
(the power to which the base is raised).Base Case:
Check if
exponent
is equal to 0. -
If true, return 1 (any number raised to the power of 0 is 1).
Recursive Case:
-
If
exponent
is not equal to 0:Return the result. -
Multiply the
base
by the result of the recursive call topower
with parametersbase
andexponent - 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
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
4.5
2.3^4.5 = 42.44
Demonstration
C++ Programing Example to Calculate Power of a Number-DevsEnv