C bootcamp · Lab 40

Power by recursion

mediumRecursion12 minLesson: Recursion

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Write long power(int a, int b) that returns a raised to b, using recursion. Anything to the power 0 is 1.

main already reads a and b and prints the result. Do not use a loop — recurse.

Input. Two integers a and b, with b ≥ 0.

Output. One integer: a^b.

Constraints

  • 0 ≤ b ≤ 12

Examples

Example 1
Input
2 10
Output
1024
Example 2
Input
5 0
Output
1
Hint
  1. Base case: if (b == 0) return 1;
  2. return a * power(a, b - 1);
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

long power(int a, int b) {
  if (b == 0) return 1;
  return a * power(a, b - 1);
}

int main(void) {
  int a, b;
  if (scanf("%d %d", &a, &b) == 2) {
    printf("%ld\n", power(a, b));
  }
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.