A Loop Example Using a Function Return Value
The last example in this chapter uses 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 n to the p power, you have to multiply n times itself p times. This is a natural task for a loop. You ...
Get C Primer Plus, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.