In this tutorial, you will learn how to write C program to calculate power of a number. There are two ways you can calculate power of a number, using loop or using pow() function.
Example 1: Program to calculate power of a number using loop
In this example, we are using while loop and inside while loop we are decrementing the exponent (variable exp
) by 1 and multiplying the number by itself. The loop keeps iterating until exp
becomes zero. This way if the exponent is 4 the number gets multiplied by itself 4 times, which is what we need for calculating the power of a number.
#include <stdio.h>
int main() {
int number, exp;
long double result = 1.0;
printf("Enter the number: ");
scanf("%d", &number);
printf("Enter exponent: ");
scanf("%d", &exp);
//storing the exponent value in a temporary variable
//to perform some arithmetic operations on it.
int temp = exp;
//Multiplying the number by itself, until the "temp"
//that contains "exp" value become zero.
while (temp != 0) {
result *= number;
--temp;
}
printf("%d to the power %d is: %.0Lf", number, exp, result);
return 0;
}
Output:
Example 2: Program to calculate power of a number using pow() function
In this example, we are calculating the power of a number using pow()
function. This function belongs to the math.h
header file so be sure to include this header file when using the pow()
function.
#include <math.h>
#include <stdio.h>
int main() {
int number, exp, result;
printf("Enter the number: ");
scanf("%d", &number);
printf("Enter exponent: ");
scanf("%d", &exp);
// Calculating power using pow() function
result = pow(number, exp);
//displaying result
printf("%d to the power %d is: %d", number, exp, result);
return 0;
}
Output: