Skip to main content

exp(x,y) using recursion

Short answer

Recursive power: if y==0 return 1, else return x * exp_xy(x, y-1). For exp(2,3), the result is 8.

Write a program to calculate the exp(x,y) using recursive function without using pow() function. [Example: exp(2,3)=2^3 i.e. 222=8.]

Idea. x^y = x × x^(y−1), and x^0 = 1. The function calls itself with y reduced by one until y becomes 0, then the products are returned back one by one.

For exp(2,3): 2 × exp(2,2) = 2 × (2 × exp(2,1)) = 2 × (2 × (2 × exp(2,0))) = 2 × 2 × 2 × 1 = 8.

#include <stdio.h>

/* x raised to y (y >= 0) by recursion */
long exp_xy(int x, int y)
{
    if (y == 0)                 /* base case: x^0 = 1 */
        return 1;
    return x * exp_xy(x, y - 1);
}

int main(void)
{
    int x, y;
    printf("Enter x and y: ");
    scanf("%d %d", &x, &y);
    if (y < 0)
        printf("y must not be negative\n");
    else
        printf("exp(%d,%d) = %ld\n", x, y, exp_xy(x, y));
    return 0;
}

Sample run

Input: 2 3

Enter x and y: exp(2,3) = 8

The function handles y ≥ 0 only (a negative power would need 1/x^(−y) and a floating-point return type).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 6 questions →