Answer to Question #222484 in C++ for Jaguar

Question #222484
The program below contains an incomplete recursive function raised_to_power().
The function returns the value of the first parameter number of type float raised to
the value of the second parameter power of type int for all values of power greater
than or equal to 0.

1. #include <iostream>
2. using namespace std;
3. float raised_to_power( )
4. {
5. if (power < 0)
6. {
7. cout << "\nError - can't raise to a negative power\n";
8. exit(1);
9. }
10. else if ( )
11. return ( );
12. else
13. return (number * raised_to_power(number, power - 1));
14. }
15. main()
16.
17. float answer = raised_to_power(4.0,3);
18. cout << answer;
19. return 0;
20.}

(a) Complete the function header in line 3.
(b) Using the fact that any value raised to the power of 0 is 1, complete the base
case in line 10 and 11.
(c) Why do we need a base case in a recursive function?
(d) What is the purpose of the general case?
1
Expert's answer
2021-08-04T01:53:46-0400

(a) Answer:

int number, int power

explanation: Declaring the input parameters


(b) Answer:

Line 10:

power == 0

explanation: when power becomes 0 will stop the recursion

Line 11:

1

explanation: for multiplication, we have to send back 1, so it can power it with 1


(c) Why do we need a base case in a recursive function?

Answer:

Because we have to stop recursive function without base case recursive function will call itself infinitely.


(d) What is the purpose of the general case?

Answer:

To stop calling recursive function for unwanted results.

Here is the complete code with a solution:

#include <iostream>
using namespace std;
float raised_to_power(int number, int power)
{
    if (power < 0)
    {
        cout << "\nError - can't raise to a negative power \n";
        exit(1);
    }
    else if (power == 0)
            return (1);
        else
            return (number * raised_to_power (number, power - 1));
}
main()
{
    float answer = raised_to_power (4.0,3);
    cout << answer;
    return 0;
}

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