Advertisement
Syndragonic

Display 14.3 CS311

Nov 3rd, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.54 KB | None | 0 0
  1. //Program to demonstrate the recursive function power.
  2.  #include <iostream>
  3.  #include <cstdlib>
  4.  using namespace std;
  5.  int power(int x, int n);
  6.  //Precondition: n > = 0.
  7.  //Returns x to the power n.
  8.  int main( )
  9.  {
  10.  for (int n = 0; n < 4; n++)
  11.  cout << "3 to the power " << n
  12.  << " is " << power(3, n) << endl;
  13.  return 0;
  14.  }
  15.  //uses iostream and cstdlib:
  16. int power(int x, int n)
  17.  {
  18.  if (n < 0)
  19.  {
  20.  cout << "Illegal argument to power.\n";
  21.  exit(1);
  22.  }
  23.  if (n > 0)
  24.  return ( power(x, n - 1) * x);
  25.  else // n == 0
  26.  return (1);
  27.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement