Answer to Question #249686 in C++ for vishal

Question #249686

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


1
Expert's answer
2021-10-11T02:56:05-0400
#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

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS