Skip to main content

Function template power(base, exp)

Short answer

Template function power(T base, int exp) returns base^exp. If exp<0, set exp=-exp. Compute result by multiplying base exp times. For 2^3 and 2^-3, result is 8; for 1.5^2, 2.25.

Write a function template for the function power() which has two parameters base and exp and returns base^exp. The type of base is the parameter to the template and exp is int. If the exp is negative, then it must be converted to its positive equivalent. For example 2³ and 2⁻³ must both return 8.

The base type T is the template parameter and exp is an int. For a negative exponent, the sign is removed as the question requires (so 2⁻³ also returns 8).

#include <iostream>
using namespace std;

template <class T>
T power(T base, int exp) {
    if (exp < 0)
        exp = -exp;              // convert to positive equivalent
    T result = 1;
    for (int i = 0; i < exp; i++)
        result *= base;
    return result;
}

int main() {
    cout << power(2, 3) << endl;        // 8
    cout << power(2, -3) << endl;       // 8
    cout << power(1.5, 2) << endl;      // 2.25
    cout << power(2.0f, -2) << endl;    // 4
    return 0;
}

Output

8
8
2.25
4

Here power(2, 3) makes T = int, and power(1.5, 2) makes T = double. If exp is 0 the loop does not run and the result is 1.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 9 questions →