Q2. Write a C program to calculate power of a number (x,y).

There may be multiple method to calculate power of a number.

Method 1:  Using function recursion

#include<stdio.h>
int power(int a, unsigned int b);
int main()
{
    int x;
    unsigned int y;
        printf(“Enter the value of x and y to calculate x raised to the power y.\n”);
        scanf(“%d”, &x);
        scanf(“%d”, &y);
    printf("%d", power(x, y));
    return 0;
}
/* Function to calculate the power */
int power(int a, unsigned int b)
{
    if( b == 0)
        return 1;
    else if (b%2 == 0)
        return power(a, b/2)*power(a, b/2);
    else
        return a*power(a, b/2)*power(a, b/2);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.