Programming Example
Write a function that computes xn, where x is any valid number and n an integer value.
Write a function that computes xn, where x is any valid number and n an integer value.
#include <stdio.h>
#include <math.h>
double power(double , int);
int main(void)
{
double x, result;
int n;
printf("\n Enter the values of x and n \n");
printf("\n x = ? ");
scanf("%lf",&x);
printf("\n n = ? ");
scanf("%d",&n);
result=power(x,n);
printf("\n Value of x^n is %g",result);
return 0;
}
/**********************************************************************/
/* Function to compute integral powers of any valid number. */
/* First argument is any valid number, second argument is power index.*/
/**********************************************************************/
double power(double x, int n) /* function header */
{ /* function body starts here... */
double result = 1.0;
int i; /* declaration of variable result */
for(i = 1; i<=n; i++) /* computing xn */
result *= x; /* : */
return result; /* return value in 'result' to calling function*/
} /* function body ends here... */
Enter the values of x and n
x = ? 2
n = ? 3
Value of x^n is 8
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.