Why is there 1 in unsigned long fact?

Feb 18, 2015 at 8:49am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    unsigned int numb;
    unsigned long fact=1;

    cout << "Enter a number: ";
    cin  >> numb;
    for(int j=numb; j>0; j--)
        fact *= j;
    cout << "Factorial is " << fact << endl;
    return 0;
}

Last edited on Feb 18, 2015 at 8:50am
Feb 18, 2015 at 10:20am
good practice dictates that all variables should have an initialiser, but in the case of "fact" it is essential.

this is because its first use is the input to a calculation "fact *= j which is fact = fact * j

its not so important for numb because it gets set before it is used cin >> numb

But really you should initialise all of your data.
Feb 18, 2015 at 11:18am
If numb is 5, then the task is to compute 5!. At the start fact is 1. After the first loop iteration fact is 1*5, and after the next iteration it is 1*5*4, ... until fact has the value of 1*5*4*3*2*1. This is the same as 1*5!. Multiplying by one doesn't change the value so the result is 5! which is what you want. If the initial value of fact was something else then the result would not be 5!.

Last edited on Feb 18, 2015 at 11:19am
Topic archived. No new replies allowed.