C Program to calculate the power of a number

The following is a C program to compute the power of a number:

Expected Output:

1st run:

2nd run:

How it works

The following table demonstrates what happens at each iteration of the while loop, assuming base = 21 and exponent = 2.

Iteration result i
After 1st iteration result = 1 * 21 = 21   2
After 2nd iteration result = 21 * 21 = 441   4

Calculating Power using the pow() function

The above program can only calculate powers when the exponent is positive. To calculate the power of a number for any real exponent use the pow() function.

To use the pow() function make sure to include math.h header file at the top of the program.

Expected Output:

1st run:

2nd run:


Recommended Reading

Leave a Comment

%d bloggers like this: