This blog is under construction

Sunday 21 July 2013

C program to calculate power of a number using recursion

Write a C program to calculate power of a number using recursion.


  #include <stdio.h>

  /* calculates power of a number using recursion */
  void calcPower(int num, int power, int *res, int *count) {
        if (*count < power) {
                *res = *res * num;
                *count = *count + 1;

                /* recursive call */
                calcPower(num, power, res, count);
        }
        return;
  }

  int main() {
        int num, power, res = 1, count = 0;

        /* get the input value and its power from user */
        printf("Enter your input value:");
        scanf("%d", &num);
        printf("Enter your power value:");
        scanf("%d", &power);

        /* any value power 0 is 1 and 0 to the power any value is 0 */
        if (!num || !power) {
                printf("%d^%d is %d\n", num, power, num ? 1: 0);
                return 0;
        }

        /* calculates power of a number using recursion */
        calcPower(num, power, &res, &count);

        printf("%d^%d => %d\n", num, power, res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:5
  Enter your power value:3
  5^3 => 125


No comments:

Post a Comment