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.
C program to Calculate the Power of a Number
#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);
}
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:2 4
Answer = 16
Explanation
This program takes base number and exponent from user and stores in variable base and exp respectively. Let us suppose, user entered 2 and 4 respectively. Then,while loop is executed with test condition
exp!=0
. This test condition will be true and value becomes 2 after first iteration and value of exp will be decreased to 2. This process goes on and after fourth iteration, value will be equal to 16(2*2*2*2) 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