Algorithm


Power of a Number is one of the basic mathematical calculation.

Logic here to calculate the power of a number -

  1. xn = x * x(n times)
  2. 2 ^ 3 = 2 * 2 * 2 = 8
  3. 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

x
+
cmd
5 3

Output

x
+
cmd
Please Enter Number: 5
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

x
+
cmd
5 3

Output

x
+
cmd
Please Enter Number: 5
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

x
+
cmd
5 3

Output

x
+
cmd
Please Enter Number: 5
Please Enter Power: 3
Answer: 125
Advertisements

Demonstration


We've provided 3 example here for calculating power of a number in C programming language using the following way.

  1. The traditional loop and calculate the power of a number
  2. pow() function of math.h header library
  3. using Recursive function
Next
Appending into a File in C Programming