--- In [email protected], "Sangati, Ramya Govinda Reddy"
<[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> Since it is a for loop, the counter is incremented till it is equal to
> the number you input, and the expression total *= counter is executed
> till the for loop is exited.
>
> total *= counter is nothing but total = total * counter; I hope you got
> it.
>
>
>
> 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]
>
Before i clarify your doubts u have an error in the program.
And the error is
inside the for loop, the statement "counter<=number", = must be
removed. There
is no need for that.
I m just showin how it works. So u got problem with the for loop.
Inside the for loop "total=total*counter" this statement means that,
for each loop the counter will be incremented and the "total" value
will be updated. What it really mean is if u give 3 as the input,
during the first "for loop" total will be 3. How?
this is when counter is 1
total=1*3=3
u know that u have inputted 3
so inside the for loop "counter<number" is there but u have
counter=1 and number=3 so the condition inside the "for loop" is
satisfied.hence counter value will be incremented, so now the value of
counter=2
total=3*2=6
because during the first loop the value of total=3
so "total=total*counter" will work like this
total=3*2=6 (during previous loop total was 3)
After this "for loop" goes for another loop when it checks the
statement "counter<number".Now we have counter=3 and number=3,the
condition is unsatisfied so for loop terminates and the "total" is
displayed.