C Program to Calculate the Power of a Number

CodingTute

Updated on:

C Programming Examples

In this tutorial, you will learn how to calculate the Power of a Number using a C program.

C Program to Calculate the Power of a Number

#include <stdio.h>

int power(int base, int exponent) {
    if (exponent == 0) {
        return 1;
    }
    return base * power(base, exponent - 1);
}

int main() {
    int base, exponent;
    printf("Enter the base: ");
    scanf("%d", &base);
    printf("Enter the exponent: ");
    scanf("%d", &exponent);
    int result = power(base, exponent);
    printf("%d^%d = %d\n", base, exponent, result);
    return 0;
}
Run Code in Online C Compiler

Output

Enter the base: 3
Enter the exponent: 4
3^4 = 81

Explanation

The function first checks if the exponent is 0. If it is, the function returns 1, since any number raised to the power of 0 is 1. If the exponent is not 0, the function calls itself with the base and exponent – 1 as arguments, and returns the result of the base multiplied by the result of the recursive call. This continues until the exponent becomes 0, at which point the function returns 1 and the recursive calls begin to unwind, multiplying the base by each result as they return. This process calculates the power of the base raised to the exponent.

You can find more C Programming Examples here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

Exit mobile version