Comp Sci C++ Factorial Calculator Exercise Solution

Click For Summary
The discussion revolves around creating a C++ program to calculate the factorial of an integer using direct multiplication. Participants express confusion about implementing the logic, particularly regarding variable declarations and loop structure. Key insights include the necessity of initializing the factorial variable (`nfac`) correctly and ensuring the loop starts from the right index to avoid multiplying by zero. After several iterations and corrections, a successful code example is provided that calculates the factorial correctly by iterating from 2 to `n` and multiplying the results. The final solution emphasizes the importance of understanding variable scope and loop mechanics in C++.
  • #31
estro said:
You main function looks like this: int main (void), it means that your function must return an integer. [you can change it to void main (void), then you will not need any return...]


Actually, main implicitly returns 0 for C++, so (for the main function only) you may omit "return 0;"

void main(void) is not okay!

It is not what is specified by the standards.

The caller is expecting a return value, and that value should be 0 for success.

It could result in stack corruption.
 
Last edited:

Similar threads

  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 24 ·
Replies
24
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 15 ·
Replies
15
Views
2K
Replies
8
Views
2K