A Loop Example Using a Function Return Value
For the last example in this chapter, you'll design a function that calculates the result of raising a number to an integer power. (For the serious number-cruncher, the math.h library provides a more powerful power function called pow() that allows floating-point exponents.) The three main tasks in this exercise are devising the algorithm for calculating the answer, expressing the algorithm in a function that returns the answer, and providing a convenient way of testing the function.
First, let's look at an algorithm. Keep the function simple by restricting it to positive integer powers. Then, if you want to raise a to the b power, you have to multiply a times itself b times. This is a natural ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access