Bash program to find A to the power B?

In C programming, calculating A to the power B can be done using the built-in pow() function from the math library, or by implementing custom algorithms. The pow() function provides an easy way to compute powers of numbers.

Syntax

#include <math.h>
double pow(double base, double exponent);

Method 1: Using pow() Function

The pow() function from math.h calculates base raised to the power of exponent −

Note: When using pow() function, you need to link the math library by adding -lm flag during compilation: gcc program.c -lm
#include <stdio.h>
#include <math.h>

int main() {
    int a = 5;
    int b = 6;
    double result = pow(a, b);
    
    printf("%d raised to the power %d = %.0f
", a, b, result); return 0; }
5 raised to the power 6 = 15625

Method 2: Using Iterative Approach

We can implement power calculation without using the math library by multiplying the base number repeatedly −

#include <stdio.h>

int power(int base, int exponent) {
    int result = 1;
    for (int i = 0; i < exponent; i++) {
        result *= base;
    }
    return result;
}

int main() {
    int a = 5;
    int b = 6;
    int result = power(a, b);
    
    printf("%d raised to the power %d = %d
", a, b, result); return 0; }
5 raised to the power 6 = 15625

Method 3: Using Recursive Approach

Power calculation can also be implemented using recursion where the function calls itself −

#include <stdio.h>

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

int main() {
    int a = 5;
    int b = 6;
    int result = power(a, b);
    
    printf("%d raised to the power %d = %d
", a, b, result); return 0; }
5 raised to the power 6 = 15625

Comparison

Method Time Complexity Space Complexity Pros Cons
pow() function O(1) O(1) Built-in, handles floating point Requires math library
Iterative O(n) O(1) Simple, no library needed Integer overflow for large numbers
Recursive O(n) O(n) Easy to understand Stack overflow for large exponents

Conclusion

C provides multiple ways to calculate power: the pow() function for general use, iterative approach for integer calculations, and recursive method for educational purposes. Choose the method based on your specific requirements and constraints.

Updated on: 2026-03-15T11:02:09+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements