Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using C++ (microsoft visual studios 2013) create a program with comments (//comm

ID: 3811934 • Letter: U

Question

Using C++ (microsoft visual studios 2013) create a program with comments (//comments) with the following instruction:

Create a program with a recursive method called power (base, exponent) that when invoked returns the answer of the base raised to the power of the exponent. Example - power(3,4) would equal 3*3*3*3. Remember, you must write the method, do not just use a math library function. Assume the exponent must be greater than or equal to 1 and send an error message should the exponent not meet this criteria. Display the answer to the screen.

Explanation / Answer

#include <iostream>
using namespace std;

int power (int base,int exponent) {
if(exponent <1) {
return -1;
}
else if( exponent == 1){
return base;
}
else{
return base * power(base, exponent-1);
}
}

int main()
{
int result = power(3,4) ;
if(result == -1){
cout<<"Invalid exponent. exponent must be greater than or equals 1"<<endl;
}
else{
cout<<"Result: "<<result<<endl;
}

return 0;
}

Output:

sh-4.2$ g++ -o main *.cpp                                                                                                                                                                                                                                                

sh-4.2$ main                                                                                                                                                                                                                                                             

Result: 81

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote