This blog is under construction

Monday 8 July 2013

C program to calculate x power y

Write a C program to calculate x power y.


  #include <stdio.h>

  int main() {
        int x, y, i, result = 1;

        /* get the input for x and y */
        printf("X power Y Calculation:\n");
        printf("Enter the value for x:");
        scanf("%d", &x);
        printf("Enter the value for y:");
        scanf("%d", &y);

        /* result is 0 if x is 0 */
        if (x == 0) {
                printf("Result is 0\n");
                return 0;
        }

        /* if power value is 0, result is 1 */
        if (y == 0) {
                printf("Result is 1\n");
                return 0;
        }

        /* calculate x power y */
        for (i = 0; i < y; i++) {
                result = result * x;
        }

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



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  X power Y Calculation:
  Enter the value for x:2
  Enter the value for y:5
  2 power 5 is 32






See Also:

No comments:

Post a Comment