Next: Call-by-value parameters Up: Introduction to User-defined functions Previous: Example function: sum of


Example Function: Raising to the power

This function returns the value of its first parameter raised to the power of its second parameter. The second parameter is an integer, but may be 0 or negative.
float power(float x, int n)
  {
    float product = 1.0;
    int absn;
    int i;
    if ( n == 0)
      return 1.0;
    else
      {
       absn = int(fabs(n));
       for (i = 1; i <= absn; i++)
         product *= x;
       if (n < 0)
         return 1.0 / product;
       else
         return product;
      }
  } // end of power
Download program.
A typical use of the power function is shown below
float x, y;
int p;
cout << "Enter a float and an integer: ";
cin >> x >> p;
y = power(x, p);
y = power(x + y, 3);
Download program.



Next: Call-by-value parameters Up: Introduction to User-defined functions Previous: Example function: sum of