Advertisement
Giuseppe_De_Rosa

C++ recursive function

May 18th, 2021
853
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.42 KB | None | 0 0
  1. // Factorial of n = 1*2*3*...*n
  2.  
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. int factorial(int);
  7.  
  8. int main() {
  9.     int n, result;
  10.  
  11.     cout << "Enter a non-negative number: ";
  12.     cin >> n;
  13.  
  14.     result = factorial(n);
  15.     cout << "Factorial of " << n << " = " << result;
  16.     return 0;
  17. }
  18.  
  19. int factorial(int n) {
  20.     if (n > 1) {
  21.         return n * factorial(n - 1);
  22.     } else {
  23.         return 1;
  24.     }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement