C program to Calculate the Power of a Number

This program below takes two integers from user, a base number and an exponent. For example: In case of 23, 2 is the base number and 3 is the exponent of that number. And this program calculates the value of baseexponent.

Source Code to Calculate Power


/* C program to calculate the power of an integer*/
#include <stdio.h>
int main()
{
  int base, exp;
  long long int value=1;
  printf("Enter base number and exponent respectively: ");
  scanf("%d%d", &base, &exp);
  while (exp!=0)
  {
      value*=base;  /* value = value*base; */
      --exp;
  }
  printf("Answer = %d", value);
}

Output

Enter base number and exponent respectively: 3
4
Answer = 81

Explanation

This program takes base number and exponent from user and stores in variable base and exp respectively. Let us suppose, user entered 3 and 4 respectively. Then, while loop is executed with test condition exp!=0. This test condition will be true and value becomes 3 after first iteration and value of exp will be decreased to 3. This process goes on and after fourth iteration, value will be equal to 81(3*3*3*3) and exp will be equal to 0 and while loop will be terminated. Here, we have declared variable value of type long long int because power of a number can be very large.

This program can only calculate the power if base power and exponent are integers. If you need to the calculate power of a floating point number then, you can use pow() function.