Hello everyone. I am reading C++ Demystified and am on the chapter about the for loop. I am using this code
#include<iostream>
using namespace std;
int main()
{
int num, counter, total = 1;
cout << "Enter a number: ";
cin >> num;
cout << "The factorial of " << num << " is ";
for (int counter = 1; counter <=num; counter++)
total = total*counter;
cout << total << endl;
return 0;
}
I am curious as to why the above code would work correctly and the code below does not
#include<iostream>
using namespace std;
int main()
{
int num, counter, total = 1;
cout << "Enter a number: ";
cin >> num;
cout << "The factorial of " << num << " is ";
for (int counter = 1; counter <=num; counter++)
total = counter; //change is here
cout << total << endl;
return 0;
}
Has the value of total been change from 1 somewhere? If not then how is
total*=counter
different from
total = counter
?