(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;
}
Comments
Leave a comment