C Program: Power of a Number

When $n$ is a positive integer, an integer $a$ multiplied to itself $n$ times is represented by $a^{n}$. $a$ is called the base and $n$ is known as exponent.

The result of the product is known as power.

c program power of a number

When $n$ is a whole number,

$a^{2} = a \times a$

$a^{3} = a \times a \times a$

$a^{n} = a \times a \times a ... \times a$

When $n = 0$,

$a^{0} = 1$

In the below C program, we create a function called power() which computes the power of an entered number to some desired exponent by recursion.

				
				#include <stdio.h>

				long power (int, int);

				int main() {
				    int exp, n;

				    printf("Number: ");
				    scanf("%d", &n);
				    printf("Exponent: ");
				    scanf("%d", &exp);

				    printf("%d^%d = %ld \n", n, exp, power(n, exp));
				    return 0;
				}

				long power (int number, int exponent) {
				    if (exponent) {
				        return (number * power(number, exponent - 1));
				    } else {
				        return 1;
				    }
				}
				
			

We run the above program to find $3^{4}$, which gives the result as follows:

				
					$ ./a.out
					Number: 3
					Exponent: 4
					3^4 = 81
				
			
c program power of a number output

We can also get the power of a number using the C function pow(), which takes two arguments of type double, where the first argument is the number and the second argument is the exponent. So, pow(2,3) computes $2^{3}$ and gives 8.

The program below computes the power of a number using the pow() function.

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

				int main() {
				    double n, exponent, result;
				    printf("Number: ");
				    scanf("%lf", &n);
				    printf("Exponent: ");
				    scanf("%lf",&exponent);

				    printf("%.1lf^%.1lf = %.2lf \n", n, exponent, pow(n,exponent));
				    return 0;
				}