Written in C++; need help finalizing by program. The parts in bold is what I can
ID: 3568645 • Letter: W
Question
Written in C++; need help finalizing by program. The parts in bold is what I can't seem to put together. I added my code below. Please help if you can :)
Write a function that uses recursion to raise a number to a power. The function should accept two arguments, the number to be raised and the exponent. Assume that the exponent is a nonnegative integer. Show that this function works correctly for several values.
#include<iostream>
using namespace std;
int power (int x, int n);
int main()
{
//declaration of variables
int base;
int exponent, pow;
cout<<"Enter a base value: ";
cin>>base;
cout<<"Enter an exponent value: ";
cin>>exponent;
cout<<base<<" raised to "<<exponent<<" is: "
<<power(base,exponent)<<endl;
system("pause");
return 0;
}
// Functions for x and n
int power(int x, int n)
{
if(n ==0)
return 1;
else
return x * power(x, n -1);
}
//end
Explanation / Answer
#include <iostream.h>
long int power (int x, int n);
int main()
{
//declaration of variables
int base;
int exponent, pow;
cout<<"Enter a base value: ";
cin>>base;
cout<<"Enter an exponent value: ";
cin>>exponent;
cout<<base<<" raised to "<<exponent<<" is: "
<<power(base,exponent)<<endl;
//system("pause");
return 0;
}
// Functions for x and n
long int power(int x, int n)
{
if(n ==0)
return 1;
else
return x * power(x, n -1);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.