- 2069 Chaitra · 4 marks
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)
Related questions
- Correct program: do-while and pow · Computer Programming, chapter 3
- Recursive function and how it works · Computer Programming, chapter 6 · asked 3×
- Series 1+11+111+… by recursion · Computer Programming, chapter 6
- Sum of digits using recursion · Computer Programming, chapter 6
- Armstrong number using recursion · Computer Programming, chapter 6
- Is recursion slow; recursive vs non-recursive · Data Structure and Algorithm, chapter 5
- Function template power(base, exp) · Object Oriented Programming, chapter 9
- Recursion; iterative vs recursive choice · Data Structure and Algorithm, chapter 5
- Normal vs recursive function · Data Structure and Algorithm, chapter 5