-1

in c++, when I am making nested For loop and I am trying to calculate the factorial...I don't get the correct factorials...I don't know why. For example factorial of 5 is 120 but here it results in 34560. why? and here is the code:

int fact=1;
    
for (int number=1; number<=10; number++) {
    for (int i=1; i<=number; i++)
       
           fact=fact*i;
           
           cout <<"factorial of "<<number<<"="<<fact<<"\n";
}      

here is it pictured: nested For loop

timrau
  • 22,578
  • 4
  • 51
  • 64
john
  • 19
  • 1
  • 5
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jason Oct 12 '22 at 17:50
  • 1
    You are using OnlineGDB. A fundamental skill of programmers of all levels is [knowing how to step through your code in a debugger](https://stackoverflow.com/questions/25385173) like GDB. You would have found your mistake very quickly. – Drew Dormann Oct 12 '22 at 17:57

1 Answers1

5

You need to re-initialize fact for each number.

int fact=1;
    
for (int number=1; number<=10; number++) {
    fact = 1;
    for (int i=1; i<=number; i++)
       
           fact=fact*i;
           
           cout <<"factorial of "<<number<<"="<<fact<<"\n";
}  
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880