 # C Programming Code Examples

## C > Functions Code Examples

### C program to find power of a number using recursion

``` C program to find power of a number using recursion Write a C program to input a number from user and find power of given number using recursion. How to find power of a number using recursive function in C programming. First give a meaningful name to our recursive function say pow(). The function must accept two numbers i.e. base and exponent and calculate its power. Hence, take two parameters for base and exponent, say pow(double base, int exponent);. Finally the function should return base ^ exponent i.e. a double type value. After declaring pow() function its time to define logic to find power recursively. There can be three cases while calculating power of a number. If exponent is 0, then power is 1. This is the base condition of our recursive function. If exponent is negative, then power is 1 / (x ^ -y). Which uses recursive call to pow() function for computing the value of (x ^ -1) i.e. 1 / pow(base, -expo). If exponent is positive, then calculate power normally using x ^ y. Computing x ^ y also makes a recursive call i.e. base * pow(base, expo - 1) #include <stdio.h> /* Power function declaration */ double pow(double base, int expo); int main() { double base, power; int expo; /* Input base and exponent from user */ printf("Enter base: "); scanf("%lf", &base); printf("Enter exponent: "); scanf("%d", &expo); // Call pow function power = pow(base, expo); printf("%.2lf ^ %d = %f", base, expo, power); return 0; } /** * Calculate power of any number. * Returns base ^ expo */ double pow(double base, int expo) { /* Base condition */ if(expo == 0) return 1; else if(expo > 0) return base * pow(base, expo - 1); else return 1 / pow(base, -expo); } ``` 