Recursion 3: Compute a^n
Write a program to compute a^n (a power n) using recursion.
Note:
Refer to the problem requirements.
Shell Scripting Function Specifications:
Use the function name as computePower() and the 2 integer arguments.
This function returns an integer value that is 'a power n'.
Function specification:
int computePower(int a,int n)
Input and Output Format:
Input consists of 2 integers.
The output is the a power n.
Refer sample input and output for formatting specifications.
Sample Input and Output:
[All text in bold corresponds to input and the rest corresponds to output.]
Enter the value of a
2
Enter the value of n
8
The value of 2 power 8 is 256
#include <iostream>
using namespace std;
int computePower(int a, int n)
{
if (n == 1)
{
return a;
}
else
{
return a * computePower(a, n - 1);
}
}
int main()
{
int a, n;
cout << "Enter the value of a:\n";
cin >> a;
cout << "Enter the value of n:\n";
cin >> n;
cout << "The value of " << a << " power " << n << " is " << computePower(a, n) << '\n';
return 0;
}
Example:
Enter the value of a:
2
Enter the value of n:
8
The value of 2 power 8 is 256
Comments
Leave a comment