Exercise 4.1.1 (Without fear)

Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N. For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120. (Hint: Use a for loop as described in Charter 3)

Please help me, my slowly reader is sometimes problem because I still don't get it all. Thanks.
What do you have?
for(int i =1;i<=number;++i)
{
result*=i;
}
If you had a little bit of knowledge about functions, you could use a recursive function too. Anyways, that wouldn't be better.

As @Darkmaster said, the required version for calculating the factorial in your exercise is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int N;
    long long result = 1;
    
    cout << "Give N = "; cin >> N;

    /*
         We will calculate RESULT = RESULT * N * N-1 * N-2 * ... * 2 * 1;
         The reason for which RESULT must be initialised to 1 is that before initializing
        the variable has garbage values, meaning that on that spot on memory there could be
        any values stored.
    */
    for (int i = N; i >= 1; i--)
    {
        result = result * i;
    }

    cout << N << "! = " << result << endl;
    
    return 0;
}


Best of wishes,
~ Raul ~
Last edited on
Don't forget the condition for N = 0. And something to prevent negative numbers.
Oh I understand now. Thank you guys.
Topic archived. No new replies allowed.