Building An Exponent Function
Lesson 23Author : Afrixi
Last Updated : November, 2022
an example of a function in C++ that calculates the exponent of a number:
#include <iostream>
double power(double base, int exponent) {
double result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
std::cout << power(2, 4) << std::endl; // prints 16
std::cout << power(3, 3) << std::endl; // prints 27
return 0;
}
In this example, the power
function takes two parameters: base
and exponent
. It initializes a variable result
to 1, and then enters a for loop that multiplies result
by base
for exponent
number of times. After the loop completes, the function returns the final value of result
.
In the main
function, the program calls the power
function twice with different parameters, and prints the results to the console using std::cout
. The program then returns 0 to indicate successful execution.
You can customize the function to handle negative exponents, zero exponent, or any other special cases you need to consider for your specific use case.