Algorithm
Power of a Number is one of the basic mathematical calculation.
Logic here to calculate the power of a number -
- xn = x * x(n times)
- 2 ^ 3 = 2 * 2 * 2 = 8
- 4 ^ 3 = 4 * 4 * 4 = 64
There is also other solution in C programming for this power. There is a function called pow()
in C Programming.
Code Examples
#1 Power of a Number in C using For Loop
Code -
C Programming
#include <stdio.h>
int main(void){
int number, power, i, answer;
printf("Please Enter Number: \n");
scanf("%d", &number);
printf("Please Enter Power: \n");
scanf("%d", &power);
answer = number;
for(i = 1; i < power; i++){
answer = answer * number;
}
printf("Answer: %d\n", answer);
}
Copy The Code &
Try With Live Editor
Input
Output
Please Enter Power: 3
Answer: 125
#2 Power of a number using pow() function on math library in C
Code -
C Programming
#include <stdio.h>
#include <math.h>
int main(void){
int number, power, answer;
printf("Please Enter Number: \n");
scanf("%d", &number);
printf("Please Enter Power: \n");
scanf("%d", &power);
answer = pow(number, power);
printf("Answer: %d\n", answer);
}
Copy The Code &
Try With Live Editor
Input
Output
Please Enter Power: 3
Answer: 125
#3 Power of a Number in C using Recursion
Code -
C Programming
#include <stdio.h>
int calculatePower(int number, int power) {
if (power != 0){
return (number * calculatePower(number, power - 1));
}
else{
return 1;
}
}
int main(void){
int number, power, answer;
printf("Please Enter Number: \n");
scanf("%d", &number);
printf("Please Enter Power: \n");
scanf("%d", &power);
answer = calculatePower(number, power);
printf("Answer: %d\n", answer);
}
Copy The Code &
Try With Live Editor
Input
Output
Please Enter Power: 3
Answer: 125
Demonstration
We've provided 3 example here for calculating power of a number in C programming language using the following way.
- The traditional loop and calculate the power of a number
pow()
function of math.h header library- using Recursive function