Lab 12 Introduction to Functions
Task 1, Developing Simple Functions:
- Define a function called power_of_two that has no parameters.
When called it should use a loop to print 2 to the first power, 2 to
the second power... up to 2 to the fifth power -- one per line.
- Now you would like to make your function more general. Define a
function called power5 that has one parameter, say x. When called, it
should use a loop to print x to the first power, x to the second power
... up to x to the fifth power -- one per line.
- Write a program that prompts the user for x and prints x to the 5th power, by using your function.
Task 2, Functions that Return Values:
In general functions return values (the last two did not).
- Now
define a function called power that has two parameters, x and n. The
function should return (not print) the result of raising x to the n-th
power. Do this with a loop. In other words, to compute x to the fourth,
you would start with an accumulator = 1 and then multiply by x four
times. This is what has to be done in a language that does not
have an operator for exponentiation. Start by assuming that n is
a positive integer.
- Write a main program that prompts the user for x and n and prints x to the nth power, by using your function.
- When you have that working, make sure you handle
the case that n is 0 (any non-zero number raised to the zero power
gives 1). You may assume n is a nonnegative integer (not too large!).