SHARE
TWEET

Untitled

a guest Mar 19th, 2019 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* assignment:  modify the code below by adding a recursive function
  2.  
  3.     factorial(n)
  4.  
  5.     Note:  the answer for the looping factorial is wrong for integers > 12.  Why?
  6.     What happens if we change fact from an int to a long?  to a float?  to a double?
  7.     If you use a float or a double, when is the answer not exactly correct?
  8.  
  9. */
  10.  
  11. #include <iostream>
  12. #include <iomanip>
  13. using namespace std;
  14.  
  15.  
  16. //......................put your factorial prototype here
  17.  
  18. int factorial(int);
  19. //......................
  20.  
  21. int main(void)
  22. {
  23.  
  24.     int n, n2, fact;
  25.  
  26.     cout << "enter an integer number: "<<endl;
  27.     cin >> n;
  28.  
  29.     n2 = n;
  30.  
  31.  
  32.     // calculate n factorial with a loop:
  33.  
  34.     fact = 1;
  35.     while (n2 > 1)
  36.     {
  37.         fact *= n2;
  38.         n2--;
  39.     }
  40.  
  41.     cout << n << " factorial is: " << fact << endl;
  42.  
  43.             // now uncomment the line below, and do it using your recursive function:
  44.  
  45.   fact = factorial(n);
  46.  
  47.     cout << n << " recursive factorial is: " << fact << endl;
  48.  
  49.     return 0;
  50.  
  51. }
  52.  
  53. //...................... add your recursive factorial function here
  54. int factorial(int n)
  55. {
  56.     if(n!=0)
  57.     {
  58.     return n*factorial(n-1);
  59.     }
  60.     else
  61.     {
  62.     return 1;
  63.     }
  64. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top