### Recursive functions

This is my function, it compiles but when i run it, comes out as testing power, segmentation fault. it is suppose to print 3^9= 19683

#include <iostream>
using namespace std;

int power(int x, int n) {
if (n == 1) return x;
return power(3,9);
}

int main ()
{
//power:
cout << "Testing power:" << endl;
int x = 3, n = 9;
cout << x << "^" << n << " = " << power (x, n) << endl << endl;
}

In your recursive call you hardcoded numbers so it will just run forever. Also, you need to be doing things with the previous function returns. Putting
 `` `` ``return power(x,n-1);``

will just return x, regardless of the value for n.

Your call in the function should be...
 `` `` ``return x * power(x,n-1);``
Last edited on
Thank you! It worked! Can you help me out with this one also? This is my function. I need to write a recursive function to print a number digit by digit, seperated by spaces.

#include <iostream>
using namespace std;

int printNumber(int x) {
if (x <10) return x;
return printNumber(x % 10);

int main ()
{
//printNumber:
cout << "Testing printNumber:" << endl;
printNumber (1000); //prints 1 0 0 0
cout << endl;
printNumber (19683); //prints 1 9 6 8 3
cout << endl;

return 0;
Topic archived. No new replies allowed.