Home > Software engineering >  nested For loop pattern in c
nested For loop pattern in c

Time:10-13

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

CodePudding user response:

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";
}  
  • Related