C Program to Calculate Power of a Number Using Loop
This program calculates the power of a given base number raised to an exponent using a simple loop instead of the built-in pow() function.
Concept Overview
To calculate power iteratively, we multiply the base number by itself exponent times. This approach avoids using the math library and is a good exercise for beginners to understand loops.
Program
C
#include <stdio.h>
int main() {
int base, exponent;
long long result = 1;
printf("Enter base number: ");
scanf("%d", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
for(int i = 1; i <= exponent; i++) {
result *= base;
}
printf("Result: %lld\n", result);
return 0;
}
How It Works
The program initializes a variable 'result' to 1. It then uses a for loop that runs from 1 to the value of 'exponent'. In each iteration, it multiplies 'result' by 'base'. After the loop completes, 'result' contains the value of base raised to the power of exponent.
Output
Enter base number: 2 Enter exponent: 5 Result: 32
Explanation
- Start with result = 1.
- Multiply result by base in each iteration of a for loop running exponent times.
- After the loop ends, result contains base^exponent.
- This method works for positive integer exponents.
Note: Note: For negative exponents, the result would be a fraction (1/power). This program currently handles only non-negative exponents.
Codecrown