C program to find power of any number using recursion

Write a C program to input any number from user and find the power of given number using recursion. How to find power of any given number using recursive function in C programming. Finding x to the power y (xy) using recursion in C programming.

Example:
Input any number: 5
Input power: 2
Output: 25

Also try this program using other programming techniques - C program to find power using pow() function.
C program to find power of any number using loops.

Required knowledge

Basic C programming, Functions, Recursion

Program

/**
 * C program to find power of any number using recursion
 */

#include <stdio.h>


/* Power function declaration */
double pow(double num, int power);


int main()
{
    int x, y;
    double power;
    
    /*
     * Reads two integer from user
     */
    printf("Enter any number: ");
    scanf("%d", &x);
    printf("Enter power of the number: ");
    scanf("%d", &y);
    
    power = pow(x, y); //Calls pow function
    
    printf("%d raised to %d = %.2f\n", x, y, power);
    
    return 0;
}


/**
 * Finds power of any number (Computes x raised to power y).
 * @param num Integer whose power is to be calculated
 * @param power Raised to num
 * @return num raised to power.
 */
double pow(double num, int power)
{
    if(power == 0)
        return 1;
    return num * pow(num, power-1);
} 


Output
Enter any number: 10
Enter power of the number: 3
10 raised to 3 = 1000.00

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment