Factorial in C++ - recursively

<<algorithm

 

fact rec en

#include <iostream>
using namespace std;

unsigned int factorial(unsigned int n) {
  if(n>1)
    return n*factorial(n-1);
  else
    return 1;
}

int main(int argc, char *argv[]) {
   unsigned int n, f;
   cout<<"n = ";
   cin>>n;
   f=factorial(n);
   cout<<n<<"! = "<<f<<endl;
   char c;
   cin>>c;
}

 


In the first line of the program, we include the header file for the iostream library (input-output streams). This is necessary because later in the program we'll want the ability to write to the screen (cout) and read input data from the keyboard (cin). In line 2, we inform the compiler that we'll be using names defined in the std namespace in the program (these will be: cin, cout, endl). If we didn't do this, it would be necessary to use the longer qualified name format (std::cin, std::cout, std::endl).

In line 4, we declare a function named factorial, which takes one integer parameter (n) and returns an integer result. The function body—the set of instructions executed by the program after the function is called—is contained between the curly braces { at the end of line 4 and } on line 9.

In line 5, we check if n is greater than 1—block (3) of the algorithm. If it is, then in line 6, we set the function's result as n multiplied by the value of the factorial function (the same factorial function we are currently defining) for n minus 1 (4). At this point, the factorial function calls itself. Such a function is called a recursive function. If n is not greater than 1, then in line 8 we set the function's result equal to 1 (the condition for ending the recursion)—block (5).

In C++, program execution starts with the main function. Line 11 contains the start of the main function definition; this is the beginning of our algorithm's implementation (START block (1)). In the following line, we declare two integer variables (n and f (result)).

Lines 13 through 14 implement the input/output operation (2), where the input data—the argument for the factorial function—is retrieved.

In line 15, we assign the result of the factorial function, called with the argument n, to the variable f.

In line 16, we print the obtained result (input-output block (6)).

The instructions in lines 17-18 have no bearing on the execution of the algorithm. They serve to pause the program until an arbitrary character is entered and the Enter key is pressed, which prevents the program window from closing immediately.

The curly brace } on line 19 ends the main function and simultaneously terminates the operation of the entire program (the algorithm's STOP block (7)).