Write C++ code to complete RaiseToPower(). Sample output if userBase is 4 and us
ID: 3575292 • Letter: W
Question
Write C++ code to complete RaiseToPower(). Sample output if userBase is 4 and userExponent is 2 is shown below. Note: This example is for practicing recursion; a non-recursive function, or using the built-in function pow(), would be more common. 4^2 = 16
#include <iostream>
using namespace std;
int RaiseToPower(int baseVal, int exponentVal){
int resultVal = 0;
if (exponentVal == 0) {
resultVal = 1;
}
else {
resultVal = baseVal * /* Your solution goes here */;
}
return resultVal;
}
int main() {
int userBase = 0;
int userExponent = 0;
userBase = 4;
userExponent = 2;
cout << userBase << "^" << userExponent << " = "
<< RaiseToPower(userBase, userExponent) << endl;
return 0;
}
Explanation / Answer
#include <iostream>
#include <cmath> //cmath contains definition of pow()
using namespace std;
int RaiseToPower(int baseVal, int exponentVal){ //recursive function
int resultVal = 0;
if (exponentVal == 0) {
resultVal = 1;
}
else {
resultVal = baseVal * RaiseToPower(baseVal,exponentVal-1);
}
return resultVal;
}
int RaiseToPowerIterative(int baseVal,int exponent) //non recursive function
{
int resultVal =1;
for(int i=1;i<=exponent;i++)
{
resultVal = resultVal *baseVal;
}
return resultVal;
}
int main() {
int userBase = 0;
int userExponent = 0;
userBase = 4;
userExponent = 2;
cout<<" Using recursion ";
cout << userBase << "^" << userExponent << " = "
<< RaiseToPower(userBase, userExponent) << endl;
cout<<" Without recursion ";
cout << userBase << "^" << userExponent << " = "
<< RaiseToPowerIterative(userBase, userExponent) << endl;
cout<<" Using pow() function ";
cout << userBase << "^" << userExponent << " = "
<< pow(userBase, userExponent) << endl;
return 0;
}
output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.