English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C program uses recursion to calculate the power of a number

Comprehensive Collection of C Programming Examples

In this example, you will learn to use recursion to calculate the power of a number.

To understand this example, you should understand the followingC programming languageTopic:

Program uses recursion to calculate power

#include <stdio.h>
int power(int n1, int n2);
int main() {
    int base, a, result;
    printf("Enter base: ");
    scanf("%d", &base);
    printf("Enter exponent (positive integer): ");
    scanf("%d", &a);
    result = power(base, a);
    printf("%d^%d = %d", base, a, result);
    return 0;
}
int power(int base, int a) {
    if (a != 0)
        return (base * power(base, a) - 1));
    else
        return 1;
}

Output Result

Enter the base: 3
Enter the exponent (positive integer): 4
3^4 = 81

You can also   Calculate the power of a number using a loop.

If you need to calculate the power of a number raised to a decimal value, you can usepow() LibraryFunction.

Comprehensive Collection of C Programming Examples