Facebook Page Twitter Page LinkedIn Page
× C Examples


If power (or exponential) of number indicates how many the number is multiplied by itself to get the final number. For example:

x raised to the power 2 = x² = x*x

x raised to the power 3 = x³ = x*x*x

Method 1: Using conditional statement

In the below example, a function called Power() is created to calculate power of a number. It uses while loop to achieve this. This method can be used to calculate the power of a number where power should be a non-negative integer.

#include <stdio.h>

static void Power(double, int);

static void Power(double x, int n) {
  double finalnum = 1;
  int n1 = n;
  while(n1 > 0){
    finalnum = finalnum * x;
    n1--;
  }
  printf("%.2f raised to the power %i = %.2f\n", x, n, finalnum);
}

int main() {
  Power(3, 5);
  Power(5, 0);
  Power(6, 2);
}

The above code will give the following output:

3.00 raised to the power 5 = 243.00
5.00 raised to the power 0 = 1.00
6.00 raised to the power 2 = 36.00

Method 2: Using pow() function of C <math.h> header file

The pow() function of C <math.h> header file can also be used to calculate power of a number. It can be used to calculate xn for any value of n (n can be negative or fraction).

#include <stdio.h>
#include <math.h>

int main() {
  double x = 3, y = 5, z = 6;
  double a = 5, b = 0, c = 2;

  printf("%.2f raised to the power %.2f = %.2f\n", x, a, pow(x, a));
  printf("%.2f raised to the power %.2f = %.2f\n", y, b, pow(y, b));
  printf("%.2f raised to the power %.2f = %.2f\n", z, c, pow(z, c));
}

The above code will give the following output:

3.00 raised to the power 5.00 = 243.00
5.00 raised to the power 0.00 = 1.00
6.00 raised to the power 2.00 = 36.00




5