Index « Previous Next »

Question

Write a recursive function that accepts two numbers as its argument and returns its power. Call the function in main().

Source Code

#include <stdio.h>

int power(int, int);

int main()
{
    int x, n;

    printf("Enter a number and power you wish to raise it to: ");
    scanf("%d%d", &x, &n);

    printf("Result: %d", power(x, n));
    return 0;
}

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

Output

Enter a number and power you wish to raise it to: 6 3
Result: 216