Calculate exponentiation using function - C

Write a C program to calculate x(y+z) by using user defined function.

Solution:

Note - When we write user defined function after main function then it is mandatory to write function prototype of user defined function before main function.

#include<stdio.h>
#include<math.h>
void power(int x,int y, int z); // function prototype
int main()
{
     int x,y,z;
     printf("Enter Value of x: ");
     scanf("%d",&x);
     printf("\nEnter Value of y: ");
     scanf("%d",&y);
     printf("\nEnter Value of z: ");
     scanf("%d",&z);
     printf("--------------------\n");
     power(x,y,z);
     return 0;
}
void power(int x,int y, int z)
{
     int ans = 1, i;
     for(i = 1; i <= (y+z); i++)
          ans = ans*x;
     printf("%d ^ (%d+%d) = %d",x,y,z,ans);
}


Output:

exponentiation

Note - To calculate power we can use standard library function  pow.  This is function is included in math.h header file.

Following is an alternate way to write function using "pow function".

void power(int x,int y, int z)
{
     int ans = 1,p;
     p=y+z;
     ans=pow(x,p);
     printf("%d ^ (%d+%d) = %d",x,y,z,ans);
}