C/C++ Factorial code

In mathematics, the factorial (faktorial) of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example,

5 ! = 5 \times 4 \times 3 \times 2 \times 1 = 120 \

The value of 0! is 1, according to the convention for an empty product. I will create a C factorial code (faktorial code). We can use command :

factorial number_1 number_2

This factorial code (faktorial code) must have two input number. So, program factorial will compute factorial value from number_1 to number_2. Output from this factorial code is in integer, So, maximum output factorial from this code is 2147483648 (maximum signed integer). You can change output from integer to double if you want to compute another big number (maximum double 2.2E+308).

Save this code with name factorial.cpp :

Compile this code with command :

gcc factorial.cpp -o factorial

This is output from this factorial code (faktorial code) :

$ ./factorial 5 10
factorial from 5 to 10
factorial value = 151200

 

One thought on “C/C++ Factorial code

  1. Hi Toto,

    In other situation, you can use recursive method to do factorial calculation:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.