This blog is under construction

Sunday 7 July 2013

C program to calculate power of a number

Write a C program to calculate power of a number.


  #include <stdio.h>

  /* calculate power of a number */
  int power(int x, int y) {
        int res = 1, i;

        /* x^0 = 1 */
        if (y == 0)
                return 1;

        /* find x^y value */
        for (i = y; i > 0; i--) {
                res = res * x;
        }
        return res;
  }

  int main() {
        int x, y, result;

        /* get the input from the user */
        printf("Enter the value for x and y(x^y):");
        scanf("%d%d", &x, &y);

        /* find x^y value */
        result = power(x, y);

        /* print the result */
        printf("%d ^ %d = %d\n", x, y, result);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for x and y(x^y):2 4
  2 ^ 4 = 16





See Also:

No comments:

Post a Comment