C Program to Write a recursive C function to calculate x^y - IProgramX

Q. Write a recursive C function to calculate x^y. (Do not use standard library function) 


Program

#include <stdio.h>
int power (int, int);
int main()
{
    int pow, num;
    long result;

    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Enter it's power: ");
    scanf("%d", &pow);
    result = power(num, pow);
    printf("%d^%d is %ld", num, pow, result);
    return 0;
}

int power (int num, int pow)
{
    if (pow)
    {
        return (num * power(num, pow - 1));
    }
    return 1;
}

Output:

Enter a number: 4
Enter it's power: 5
4^5 is 1024 

Post a Comment

0 Comments