14.5k views
1 vote
Write a function that uses recursion to raise a number to a power. The function should accept two arguments: the number to be raised and the exponent. Assume that the exponent is a nonnegative integer. Demonstrate the function in a program.

IN C PROGRAM

1 Answer

3 votes

Answer:

/*

Program to computea number raised to a power using recursion

base = number and exp is the power to which the number is raised

*/

#include <stdio.h>

int power(int base, int exp);

int main(){

int base, exp;

printf("Enter base: ");

scanf("%d", &base);

printf("Enter exponent: ");

scanf("%d", &exp);

long result = power(base,exp); //function call

printf("%d raised to the power %d = %ld\\", base, exp, result);

return 0;

}

int power(int base, int exp){

//2 base cases

// if exp = 0, return 1

if (exp == 0){

return 1;

}

//if exp 1, return base

if ( exp == 1){

return base;

} //base case when expnent is 0

//otherwise return base * base to the power exp-1

return base * power(base, exp-1 );

}

Step-by-step explanation:

Write a function that uses recursion to raise a number to a power. The function should-example-1
User Witters
by
6.8k points