C Program to Calculate the Power of a Number

To understand this example, you should have the knowledge of the following C programming topics:


The program below takes two integers from the user (a base number and an exponent) and calculates the power.

For example: In the case of 23

  • 2 is the base number
  • 3 is the exponent
  • And, the power is equal to 2*2*2

Power of a Number Using the while Loop

Output

Enter a base number: 3
Enter an exponent: 4
Answer = 81

We can also use the pow() function to calculate the power of a number.


Power Using pow() Function

Output

Enter a base number: 2.3
Enter an exponent: 4.5
2.3^4.5 = 42.44

The programs above can only calculate the power of the base number if the exponent is positive. For negative exponents, use the following mathematical logic:

base(-exponent) = 1 / (baseexponent)

For example,

2-3 = 1 / (23)