// powerFunctionDemo.cpp
//
// Demonstrates power function.

#include <iostream>

using namespace std;

double power(float base, int exponent);

/*
 * int main()
 *
 * Prompts user to enter base and exponent.
 * Outputs base, exponent, and power.
 *
 * Global variables:
 *    cin -- standard input stream
 *    cout -- standard output stream
 */
int main()
{
   // Announce purpose of program:
   cout << "This program will raise a floating-point "
             << "number to an integer power." << endl;

   // Input base:
   cout << "Enter base (floating-point):>";
   float enteredBase;
   cin >> enteredBase;

   // Check input error:
   if ( !cin )  {
      cout << "You did not enter a fixed-point number." << endl;
      return 1;
   }  // if

   // Input exponent:
   cout << "Enter exponent (integer):>";
   int enteredExponent;
   cin >> enteredExponent;

   // Check input error:
   if ( !cin )  {
      cout << "You did not enter an integer." << endl;
      return 1;
   }  // if

   // Raise enteredBase to the enteredExponent power:
   double result = power(enteredBase, enteredExponent);

   // Display result:
   cout << enteredBase << " to the " << enteredExponent
               << " power is " << result << "." << endl;

   return 0;
}  // function main

/*
 * double power(float base, int exponent)
 *
 * Raises a floating-point number to a
 * specified integer power.
 *
 * Parameters:
 *    base - the number to be raised to a power.
 *    exponent - the integer exponent.
 *
 * Returns:
 *    base raised to the exponent power.
 */
double power(float base, int exponent)
{
   // If exponent is negative, do necessary conversions
   // to raise reciprocal of base to a positive power:
   if ( exponent < 0 )
   {
      exponent = 0 - exponent;
      base = 1 / base;
   }  // if exponent < 0

   // Raise base to a non-negative power:
   double product = 1;
   for ( int i = 0; i < exponent; i++ )
      product = product * base;
   return product;
}  // function power