- 2068 Chaitra · 6 marks
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)
Related questions
- Class and function template with syntax · Object Oriented Programming, chapter 9 · asked 4×
- Importance of function template · Object Oriented Programming, chapter 9 · asked 2×
- Need of template; function template overloading · Object Oriented Programming, chapter 9
- Function template: sum and average of array · Object Oriented Programming, chapter 9
- Cube of int, float, double by overloading · Object Oriented Programming, chapter 3
- LandMeasure class and sum function · Object Oriented Programming, chapter 4
- Equivalent Y-parameter of parallel two-ports · Electrical Circuit Theory, chapter 7 · asked 3×
- Equivalent Z-parameter of three series two-ports · Electrical Circuit Theory, chapter 7 · asked 3×
- Equivalent T from Y parameters of series two-ports · Electrical Circuit Theory, chapter 7
- Positive XOR equals negative XNOR · Digital Logic, chapter 2 · asked 3×