The power of a number can be calculated using the built-in pow() function. This function is available in the math.h header file and is used to calculate the value of a base raised to a given exponent.
For example, if we want to calculate 3 raised to the power of 4, the mathematical expression is 3^4, and the result is 81.
What Is the Power of a Number?
The power of a number represents how many times a number is multiplied by itself.
It consists of two main components:
- Base: The number that is multiplied repeatedly.
- Exponent: The number that specifies how many times the base is used as a factor.
For example:
Here:
- Base = 4
- Exponent = 3
- Result = 64
More examples:
| Expression | Calculation | Result |
|---|---|---|
| 2^3 | 2 × 2 × 2 | 8 |
| 3^4 | 3 × 3 × 3 × 3 | 81 |
| 5^2 | 5 × 5 | 25 |
| 10^3 | 10 × 10 × 10 | 1000 |
| 2^5 | 2 × 2 × 2 × 2 × 2 | 32 |
What Is the pow() Function in C?
The pow() function in C is a mathematical library function used to calculate the power of a number.
It is declared in the math.h header file.
Syntax:
pow(base, exponent);
Parameters:
base: Represents the number whose power needs to be calculated.exponent: Represents the power to which the base is raised.
Return value:
The pow() function returns a double value representing the calculated power.
Example:
pow(2, 3);
The above function calculates:
Therefore, the function returns 8.0.
C Program to Calculate Power Using pow() Function
The following C program takes the base and exponent as input from the user and calculates the power using the pow() function.
#include <stdio.h>
#include <math.h>
int main()
{
double base, exponent, result;
printf("Enter the base: ");
scanf("%lf", &base);
printf("Enter the exponent: ");
scanf("%lf", &exponent);
result = pow(base, exponent);
printf("%.2lf raised to the power %.2lf = %.2lf",
base, exponent, result);
return 0;
}
Output:
Enter the base: 3
Enter the exponent: 4
3.00 raised to the power 4.00 = 81.00
Explanation of the Power Program in C
- Include the
stdio.hheader file for input and output operations. - Include the
math.hheader file to use thepow()mathematical function. - Declare three variables:
base,exponent, andresultto store the input values and calculated power. - Read the base value from the user.
- Read the exponent value from the user.
- Call the
pow()function by passing the base and exponent as arguments. - Store the returned result in the
resultvariable. - Display the calculated power using the
printf()function. - Terminate the program using
return 0.