OverIQ.com

C Program to calculate the power of a number

Last updated on September 23, 2020


The following is a C program to compute the power of a number:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*******************************************
 Program to calculate the power of a number
 *******************************************/

#include<stdio.h> // include stdio.h library

int main(void)
{       
    int base, exponent, result = 1;

    printf("Enter base: ");
    scanf("%d", &base);

    printf("Enter exponent: ");
    scanf("%d", &exponent);

    int i = 1;

    while(i <= exponent)
    {
        result *= base;
        i++;
    }

    printf("%d^%d = %d", base, exponent, result);

    return 0; // return 0 to operating system
}

Try it now

Expected Output:

1st run:

1
2
3
Enter base: 21
Enter exponent: 2
21^2 = 441

2nd run:

1
2
3
Enter base: 25
Enter exponent: 4
25^4 = 390625

How it works #

The following table demonstrates what happens at each iteration of the while loop, assuming base = 21 and exponent = 2.

Iteration result i
After 1st iteration result = 1 * 21 = 21 2
After 2nd iteration result = 21 * 21 = 441 4

Calculating Power using the pow() function #

The above program can only calculate powers when the exponent is positive. To calculate the power of a number for any real exponent use the pow() function.

To use the pow() function make sure to include math.h header file at the top of the program.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/********************************************************************
 Program to calculate the power of a number using pow() the function
 ********************************************************************/

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

int main(void)
{       
    double base, exponent;       

    printf("Enter base: ");
    scanf("%lf", &base);

    printf("Enter exponent: ");
    scanf("%lf", &exponent);       

    printf("%.2f^%.2f = %.2f", base, exponent, pow(base, exponent));

    return 0; // return 0 to operating system
}

Try it now

Expected Output:

1st run:

1
2
3
Enter base: 4.5
Enter exponent: 1.2
4.50^1.20 = 6.08

2nd run:

1
2
3
Enter base: 20
Enter exponent: 2.5
20.00^2.50 = 1788.85

Recommended Reading