Function Assignment 10 — Calculate the Power of a Number Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Calculate the Power of a Number Using a Function

📑 On this page:
  • What does "power" mean, and why not use pow()?
  • The naive loop — correct but slow
  • Fast exponentiation — O(log n)
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What baseexp means in terms of repeated multiplication
  • Why pow() from <math.h> works for floating-point math but has subtle issues for exact integer results
  • How to write the naive O(exp) loop version
  • How fast exponentiation (binary exponentiation) gets the result in O(log exp)
  • The recursive expression of the same idea, which reads almost like a proof

What does "power" mean, and why not use pow()?

baseexp — usually written base^exp or pow(base, exp) — means "multiply base by itself exp times." So 2^10 = 1024, 3^4 = 81, 10^3 = 1000, and 5^0 = 1 (anything to the power of zero is 1, by convention). Negative exponents are the reciprocal: 2^-3 = 1 / 2^3 = 1/8 = 0.125.

C's <math.h> library includes a pow() function, so why write your own? A few reasons. First, pow() returns a double, which introduces floating-point rounding — for integers where you want an exact result (like 2^30 = 1073741824), you'd need to cast back from double and verify no precision was lost. Second, pow() is a library call, with overhead — for tight loops, an inline implementation can be faster. Third, and most importantly for learning: writing the function yourself teaches you how exponentiation actually works, and introduces the fast-exponentiation algorithm that shows up throughout computer science (modular exponentiation, matrix powers, RSA, etc.).

The naive loop implementation is simple: multiply base by itself exp times. That's O(exp) multiplications — for 2^1000, that's a thousand multiplications. Fast exponentiation (also called binary exponentiation) does it in O(log exp) — for 2^1000, that's about ten multiplications. That's a factor of 100 improvement, and the gap grows as the exponent grows. If you're ever computing modular powers for cryptography (like 2^1000000 mod 7919), the difference between O(n) and O(log n) is the difference between "finishes in a minute" and "finishes in microseconds."

This assignment starts with the naive version so you see the baseline, then upgrades to fast exponentiation. Both are useful. The naive version is easier to read and, for small exponents, plenty fast. The fast version is the standard idiom for anything with larger exponents — and it's the version you should reach for once you've understood it.

💡 In one line: use fast exponentiation. Start with result = 1; while exp > 0, if exp is odd, multiply result by base; square base; halve exp. Return result. That's O(log exp) multiplications.

A visual of repeated multiplication, showing that base^exp means base multiplied by itself exp times, and that squaring halves the work.

The naive loop — correct but slow

The simplest version: multiply base by itself exp times.

long long power_naive(int base, int exp) {
    long long result = 1;
    for (int i = 0; i < exp; i++) {
        result *= base;
    }
    return result;
}
                                

For power_naive(2, 10), this does ten multiplications. For power_naive(2, 1000), a thousand multiplications. For 2^1000000, a million multiplications. Each iteration is cheap, but the total work grows linearly with the exponent. That's fine for small exponents (2^10, 3^5) but slow for anything substantial.

There's also a subtle issue: the result overflows very quickly for large bases and exponents. 2^63 overflows a signed 64-bit integer (long long max is about 9.2 × 10¹⁸, and 2^63 is about 9.22 × 10¹⁸ — right at the edge). For anything larger, you'd need arbitrary-precision arithmetic. But for our purposes — moderate exponents like 2^20 or 3^15 — long long is plenty.

🎯 Why this version is included: so you can compare. The naive version is straightforward; the fast version is a bit cleverer. Seeing both side by side makes the improvement tangible. Also, the naive version is the right choice if exp is guaranteed small (say, always ≤ 10) — the added complexity of fast exponentiation isn't worth it then.

Fast exponentiation — O(log n)

Here's the key insight. To compute base^exp:

  • If exp is even: base^exp = (base^(exp/2))². Compute half the power, then square it.
  • If exp is odd: base^exp = base × base^(exp-1), and now exp-1 is even. So one multiplication, then the even case.

Either way, each step roughly halves the exponent. After O(log exp) steps, we reach exp = 0, which is the base case. That's the algorithm — and in code, it's compact:

long long power(int base, int exp) {
    long long result = 1;
    long long b = base;

    while (exp > 0) {
        if (exp % 2 == 1) {       /* exp is odd */
            result *= b;
        }
        b *= b;                   /* square the base */
        exp /= 2;                 /* halve the exponent */
    }

    return result;
}
                                

Let's trace power(2, 10):

Iteration exp result b Action
start1012—
1101410 even — skip multiply; square b; halve exp
254165 odd — multiply; square b; halve exp
3242562 even — skip multiply; square b; halve exp
411024655361 odd — multiply; square b; halve exp
end01024—Loop ends. Return 1024. ✓

Four iterations of the loop. The naive version does ten. For 2^1000, the fast version does ten iterations; the naive version does a thousand. For 2^1000000, the fast version does twenty; the naive version does a million. The gap grows dramatically with the exponent — and that's why fast exponentiation is a standard technique in competitive programming and cryptography.

A recursive version expresses the same idea more directly:

long long power_rec(int base, int exp) {
    if (exp == 0) return 1;
    if (exp == 1) return base;

    long long half = power_rec(base, exp / 2);
    if (exp % 2 == 0) {
        return half * half;
    } else {
        return half * half * base;
    }
}
                                

This reads almost like the mathematical definition: "to compute base^exp, compute base^(exp/2) twice (i.e., square it), then multiply by base if exp is odd." The recursion depth is O(log exp), so it's safe even for large exponents. Most people find the iterative version easier to follow, but the recursive one is a nice demonstration of how the algorithm naturally expresses itself.

🔍 Why does it work? Every exponent has a binary representation. 10 = 1010₂ = 8 + 2. Fast exponentiation is essentially reading off that binary representation: each bit of exp corresponds to a squaring of base, and each 1-bit corresponds to a multiplication into result. For 2^10 = 2^(8+2) = 2^8 × 2^2 = 256 × 4 = 1024. The loop does exactly this, iterating over the bits from least significant to most.

Complete C Program

Program: fast exponentiation, iterative

#include <stdio.h>

/* Function prototype */
long long power(int base, int exp);

int main(void) {
    int base, exp;

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

    if (exp < 0) {
        printf("Negative exponents are not supported in this version.\n");
        return 1;
    }

    printf("%d^%d = %lld\n", base, exp, power(base, exp));

    return 0;
}

/* Fast exponentiation */
long long power(int base, int exp) {
    long long result = 1;
    long long b = base;

    while (exp > 0) {
        if (exp % 2 == 1) {
            result *= b;
        }
        b *= b;
        exp /= 2;
    }

    return result;
}
                                    

And here's a version that supports negative exponents, returning a double:

Variant: negative exponents (returns double)

#include <stdio.h>

double power(int base, int exp) {
    if (exp == 0) return 1.0;

    int abs_exp = (exp > 0) ? exp : -exp;
    double result = 1.0;
    double b = base;

    while (abs_exp > 0) {
        if (abs_exp % 2 == 1) {
            result *= b;
        }
        b *= b;
        abs_exp /= 2;
    }

    return (exp > 0) ? result : 1.0 / result;
}

int main(void) {
    int base, exp;
    printf("Enter base and exponent: ");
    scanf("%d %d", &base, &exp);
    printf("%d^%d = %g\n", base, exp, power(base, exp));
    return 0;
}
                                    

The %g format specifier picks the most compact representation of a double — avoiding the trailing zeros that %f would produce. For 2^-3, it prints 0.125; for 2^10, it prints 1024. That's the specifier you'd want for a general-purpose power function that might return an integer or a fraction.

And a version that shows the step-by-step calculation, useful for understanding:

Variant: print each iteration

#include <stdio.h>

long long power_verbose(int base, int exp) {
    long long result = 1;
    long long b = base;

    printf("Initial: result = 1, b = %lld, exp = %d\n", b, exp);

    while (exp > 0) {
        if (exp % 2 == 1) {
            result *= b;
            printf("  exp odd  -> result *= b => result = %lld\n", result);
        } else {
            printf("  exp even -> skip\n");
        }
        b *= b;
        exp /= 2;
        printf("  square b => b = %lld; halve exp => exp = %d\n", b, exp);
    }

    return result;
}

int main(void) {
    int base, exp;
    printf("Enter base and exponent: ");
    scanf("%d %d", &base, &exp);
    printf("Result: %lld\n", power_verbose(base, exp));
    return 0;
}
                                    

Running this with 2 10 shows every step of the algorithm. It's not code you'd ship, but it's exactly the tool you want when learning — you can see how b squares each iteration and result picks up the odd-exponent contributions.

Program Output

A typical run of the first program:

Enter base and exponent: 2 10
2^10 = 1024
                                

With a larger exponent:

Enter base and exponent: 2 30
2^30 = 1073741824
                                

With exponent zero:

Enter base and exponent: 5 0
5^0 = 1
                                

With exponent one:

Enter base and exponent: 7 1
7^1 = 7
                                

With a larger base:

Enter base and exponent: 3 15
3^15 = 14348907
                                

And for the negative-exponent variant:

Enter base and exponent: 2 -3
2^-3 = 0.125
                                

And the verbose version with 2 10:

Enter base and exponent: 2 10
Initial: result = 1, b = 2, exp = 10
  exp even -> skip
  square b => b = 4; halve exp => exp = 5
  exp odd  -> result *= b => result = 4
  square b => b = 16; halve exp => exp = 2
  exp even -> skip
  square b => b = 256; halve exp => exp = 1
  exp odd  -> result *= b => result = 1024
  square b => b = 65536; halve exp => exp = 0
Result: 1024
                                

Four iterations, and the result is 1024. The verbose version makes it clear that the "if odd, multiply" step is what accumulates the odd bits of the exponent, and the "square b" step is what moves us to the next bit position. It's a natural way to read off binary representations.

Step-by-Step Explanation

Let's trace the algorithm and explain each piece.

1. The result variable

long long result = 1; — the multiplicative identity. Starting with 1 and multiplying into it is standard for accumulation loops. If you started with result = base, you'd be double-counting one iteration. Starting from 1 keeps the logic symmetric — every multiplication into result is an accumulation step, and the loop can stop cleanly when exp = 0.

2. The running square

long long b = base; — b starts at base and squares each iteration. After the first iteration, b = base². After the second, b = base⁴. After the k-th, b = base^(2^k). So the loop has access to base^1, base^2, base^4, base^8, ... — exactly the powers we need to reconstruct any base^exp from its binary digits.

3. The odd-exponent check

if (exp % 2 == 1) result *= b; — if the current lowest bit of exp is 1, we include the current power of base in the result. This is the "read off the binary representation" idea in action. For exp = 10 = 1010₂, the bits from lowest to highest are 0, 1, 0, 1. The loop multiplies result by b on the second and fourth iterations (the two 1-bits) — accumulating base^2 × base^8 = base^10.

4. The squaring step

b *= b; — square b each iteration. This is what makes the algorithm O(log n): the "current power" doubles in exponent each iteration, so O(log exp) iterations cover the entire range. If b started at base and never squared, we'd have to multiply by base separately each iteration — that's the naive version.

5. The halving step

exp /= 2; — integer division. Each iteration halves the exponent, so we're effectively walking through the binary representation from low bit to high. After O(log exp) iterations, exp reaches 0, the loop ends, and result holds the final answer.

6. Tracing power(2, 10) in slow motion

  1. Start: result = 1, b = 2, exp = 10.
  2. exp = 10 is even → skip multiply. b = 4, exp = 5.
  3. exp = 5 is odd → result = 4. b = 16, exp = 2.
  4. exp = 2 is even → skip. b = 256, exp = 1.
  5. exp = 1 is odd → result = 4 × 256 = 1024. b = 65536, exp = 0.
  6. Loop ends. Return 1024. ✓

Four iterations. The naive version would be ten multiplications. For larger exponents, the difference is dramatic: 2^30 would be 30 multiplications naive, but only 5 iterations fast. 2^1000 would be 1000 vs. 10.

7. The binary interpretation

Think of exp in binary. For exp = 10 = 1010₂, the algorithm accumulates base raised to the positions where the binary digit is 1: positions 1 and 3 (counting from 0), which are 2^1 and 2^3. So it computes base^2 × base^8 = base^10. For exp = 13 = 1101₂, it accumulates base^1 × base^4 × base^8 = base^13. This connection between exponentiation and binary representation is why the algorithm is sometimes called "binary exponentiation." Once you see it, the code writes itself.

8. Overflow

long long is 64 bits (on most systems), so it can hold up to 2^63 - 1 ≈ 9.22 × 10¹⁸. That's enough for 2^62 and most practical cases. But 2^63 overflows a signed long long. If you're computing large powers, you'd use unsigned long long (which extends the range to 2^64 - 1) or arbitrary-precision arithmetic. For this assignment, stick with long long and moderate exponents — beyond that, you're into bignum territory, which is a separate topic.

9. Why the iterative version over the recursive one?

Both are correct. The recursive version is more readable if you like functional style, but the iterative version is faster (no function call overhead) and doesn't risk stack overflow for very large exponents. Since both are O(log exp), the speed difference is small in practice — but the iterative version is standard for production code. The recursive version is worth writing once to understand the underlying recurrence; then switch to the iterative one.

10. What about pow()?

<math.h>'s pow(double, double) returns a double. For integer inputs, that means converting to double, doing the exponentiation with floating-point arithmetic (which is subject to rounding), then converting back. For 2^10, the result is exactly 1024 — no problem. For 10^20, the result exceeds double's exact integer range (about 2^53 ≈ 9 × 10¹⁵), so you'd get an approximate value, not the exact integer. Our long long version gives exact results up to 9 × 10¹⁸, which is more precise than pow() for integer inputs. That's a real advantage — and it's why hand-written power functions appear in integer-heavy code.

🔍 Try this: run power(2, 62) with both the naive and fast versions. Both should print 4611686018427387904. Then try power(2, 63) — you'll see the overflow (the result becomes negative, because 2^63 doesn't fit in a signed long long). This is a good exercise in understanding integer overflow and where the limits of the type lie.

Frequently Asked Questions

1. Why not just use pow()?

pow() returns double, which is subject to floating-point rounding. For integers where you need exact results — like 2^62 or 3^30 — pow() may give a slightly wrong answer (off by a unit in the last place, or worse). It also involves a library call and type conversions. Writing your own integer power function gives exact results, avoids library overhead, and teaches the algorithm. For floating-point math (e.g., 2.5^3.7), pow() is the right tool.

2. Why is the result type long long?

Because int overflows very quickly for powers. 2^31 already exceeds INT_MAX (which is about 2.15 billion). 2^62 is about 4.6 × 10¹⁸, which fits in long long but not in int. Using long long for the result lets you handle moderate exponents without overflow. For very large exponents, you'd need unsigned long long (extending to 2^64 - 1) or arbitrary-precision arithmetic.

3. What about negative exponents?

The integer version doesn't support them (the result would be a fraction). The double variant handles them: compute the positive power, then take the reciprocal. For example, 2^-3 = 1/2^3 = 1/8 = 0.125. The formula base^(-exp) = 1 / base^exp lets you reuse the positive-exponent code and just invert at the end. Note that floating-point reciprocals introduce rounding — 3^-1 is not exactly 1/3 but 0.333333... (to the limits of double precision).

4. What's 0^0?

Mathematically undefined — some conventions say 1, others say undefined. In most programming contexts, pow(0, 0) returns 1, and our function does too (since exp = 0 skips the loop and returns result = 1). It's a convention, not a mathematical fact. For 0^positive, the function correctly returns 0. For 0^negative, it would be division by zero — undefined behavior, so avoid it.

5. Why is fast exponentiation called "binary exponentiation"?

Because it works by reading off the binary digits of the exponent. Each iteration of the loop corresponds to one bit of the exponent, and the "if odd, multiply" step corresponds to whether that bit is 1. This is why the algorithm is O(log exp) — the loop runs once per bit, and exp has O(log exp) bits. The connection between binary representation and exponentiation is what makes the algorithm elegant and fast.

6. Can I use this for modular exponentiation?

Yes — this is the basis for base^exp mod m, which is used everywhere in cryptography. The change is tiny: instead of result *= b, write result = (result * b) % m, and instead of b *= b, write b = (b * b) % m. Taking the modulus at each step keeps the numbers small (always less than m²), preventing overflow and making the algorithm efficient for cryptographic sizes. That's the version used in RSA, Diffie-Hellman, and most of modern cryptography.

💡 Tip: Once this works, try the modular version: compute 2^1000000 mod 7919. That's a classic competitive-programming exercise, and it's exactly what you'd do to verify the performance of fast exponentiation — the naive version would take a million iterations, while the fast version takes about twenty. Seeing that speedup in action is one of those "aha" moments about algorithm design.

📖 Related Tutorials

  • Introduction to Functions in C
  • Recursion in C
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Previous: Swap Two Numbers Using a Function
  • All 33 Function Assignments

Previous Topic: -->> 9. Swap Two Numbers Using a Function   ||   Next Topic: -->> 11. Check If a Year Is a Leap Year Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.