22.5HT1 Functions Additional Exercises

Functions

Additional Exercises


  1. The following function raises an integer to a given power ( X^n )
    int power (int x, int n)
    {
            int p;
            for (p = 1; n > 0; n--)
                    p = p * x;
            return p;
    }
    

    Add a main program to prompt the user to enter a integer and the desired power then call the function, and finally print out the answer. Remember to add a function prototype.

    Revision

    The power to raise the integer to, n must be a positive integer. Check that the value entered is positive, if it is not do not let the user proceed until a positive value is entered (see notes on Iteration).

  2. The above is an iterative method of calculating the value of X^n, write a recursive function to calculate the value of a number (base) raised to a power (power). Assume the power is positive.


Back to Main Page for Lecture 6