Let me clarify it for you..
First look at how to compute the factorial mathematically then go and find
what's there in the logic
if you want to find 3! it's done as
3!= 3*2*1 which is nothing but you are multiplying all all the number till
that number starting from 1(as 0! = 1)

So in the for loop you are incrementing the counter and multiplying the
counter with the previous value of total(which will have result of previous
multiplication) and you are continuing this multiplication till counter
equals the number you've input.

Consider this computation with initial values of the variables in
parenthesis

          number(3)   total(1)    counter(1)

pass1:                    1              1
pass2:           (1*2)  2              2
pass3:           (2*3)  6              3

So at the end of the 3rd total will be 6 and in he next pass counter becomes
4 and the control comes out of for loop.

-nag.
On 3/7/07, len_kim <[EMAIL PROTECTED]> wrote:
>
>   Being new to programming and c++, I am unable to understand exactly
> what is going on in this example factorial program out of the c++
> Demystified book. When I input a 3, it returns 6 and I'm not sure how.
> The thing that confuses me is the line that says total *=counter; If
> total = 1, and counter = 3(which is the number I inputted), then total
> *=counter should read as 1 = 1 * 3 which should output a 3. Can someone
> clarify this for me?
>
> #include <iostream>
> using namespace std;
> int main()
>
> {
> int number, counter, total = 1;
> cout <<"Enter a number to see the factorial: ";
> cin >> number;
> cout << "The factorial of " << number << " is ";
> for (int counter = 1; counter <= number; counter++)
> total *= counter; //how can this return a 6 since total = 1 and counter
> = 3 ??
> cout << total;
> return 0;
> }
>
>  
>


[Non-text portions of this message have been removed]

Reply via email to