Home / Programs / Write a function that computes xn, where x is any valid number and n an integer value.
Programming Example

Write a function that computes xn, where x is any valid number and n an integer value.

👁 1,752 Views
💻 Practical Program
📘 Step by Step Learning
Write a function that computes xn, where x is any valid number and n an integer value.

Program Code

#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...     */

Output


 Enter the values of x and n

 x = ?  2

 n = ?  3

 Value of x^n is 8
 

Explanation

None

How to learn from this program

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.