C Program to Calculate the Power of a Number
In this programming tutorial, we will develop a C program to calculate the power of a number. Additionally, we’ll explore an alternative method using the pow()
function from the math library. The program will include a step-by-step explanation of the algorithm, the C code implementation, and examples demonstrating the output.
Algorithm for Calculating Power
Method 1: Using a Loop
- Input: Accept the base (
base
) and exponent (exponent
) from the user. - Initialization: Set a variable
result
to 1. - Loop:
- Multiply
result
bybase
for each iteration, repeatingexponent
times.
- Multiply
- Output: Display the calculated power (
result
).
Method 2: Using pow()
Function
- Input: Accept the base (
base
) and exponent (exponent
) from the user. - Function Call: Use the
pow()
function to calculate the power. - Output: Display the calculated power.
C Program for Calculating Power
Method 1: Using a Loop
#include <stdio.h>
int main() {
int base, exponent;
long long result = 1;
// Input base and exponent from the user
printf("Enter base: ");
scanf("%d", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
// Calculate power using a loop
for (int i = 0; i < exponent; i++) {
result *= base;
}
// Display the result
printf("%d^%d = %lld\n", base, exponent, result);
return 0;
}
Method 2: Using pow()
Function
#include <stdio.h>
#include <math.h>
int main() {
int base, exponent;
double result;
// Input base and exponent from the user
printf("Enter base: ");
scanf("%d", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
// Calculate power using pow() function
result = pow(base, exponent);
// Display the result
printf("%d^%d = %.2f\n", base, exponent, result);
return 0;
}
Output Examples
Example 1: Calculate Power Using a Loop
Enter base: 2
Enter exponent: 5
2^5 = 32
Example 2: Calculate Power Using pow()
Function
Enter base: 3
Enter exponent: 4
3^4 = 81.00
Explanation
Method 1: Using a Loop
- Input: The user provides the base (e.g., 2) and exponent (e.g., 5).
- Initialization: Variables
base
,exponent
, andresult
are initialized. - Loop: A
for
loop multipliesresult
bybase
for each iteration, repeatingexponent
times. - Output: The program displays the calculated power (
result
).
Method 2: Using pow()
Function
- Input: The user provides the base (e.g., 3) and exponent (e.g., 4).
- Function Call: The
pow()
function is called to calculate the power. - Output: The program displays the calculated power.
Conclusion
These C programs efficiently calculate the power of a number using two different methods. The first method employs a loop to perform the multiplication iteratively, while the second method utilizes the pow()
function. Run the programs with different base and exponent values to observe the results. If you have any questions or need further clarification, please feel free to ask!