# using nested for loop to print all of factorial

33 views (last 30 days)
Shuoze Xu on 16 Jun 2022
Edited: DGM on 16 Jun 2022
Hi.
I want to print the factorial of each number from 1 to 100 using a nested loop.
Here is my program.
factorials = 1; % set a varaiable named factorial
for n = 1:100 % set a nested for loop
for i= 1:n
factorials = factorials * i; % when n = 1;i = 1; f = 1*1
disp(factorials); % display results
end
end
The expected result shoule be 1, 2, 6,24........
When i run my code, the result are inf.
Why it happened?
And how to modify my code?
Thank you all.

DGM on 16 Jun 2022
Edited: DGM on 16 Jun 2022
Something like this should be a start:
for n = 1:100 % set a nested for loop
factorials = 1; % this needs to be reset inside the loop
for i = 1:n
factorials = factorials * i; % when n = 1;i = 1; f = 1*1
end
disp(factorials); % display only the final result for each n
end
1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 6.2270e+09 8.7178e+10 1.3077e+12 2.0923e+13 3.5569e+14 6.4024e+15 1.2165e+17 2.4329e+18 5.1091e+19 1.1240e+21 2.5852e+22 6.2045e+23 1.5511e+25 4.0329e+26 1.0889e+28 3.0489e+29 8.8418e+30 2.6525e+32 8.2228e+33 2.6313e+35 8.6833e+36 2.9523e+38 1.0333e+40 3.7199e+41 1.3764e+43 5.2302e+44 2.0398e+46 8.1592e+47 3.3453e+49 1.4050e+51 6.0415e+52 2.6583e+54 1.1962e+56 5.5026e+57 2.5862e+59 1.2414e+61 6.0828e+62 3.0414e+64 1.5511e+66 8.0658e+67 4.2749e+69 2.3084e+71 1.2696e+73 7.1100e+74 4.0527e+76 2.3506e+78 1.3868e+80 8.3210e+81 5.0758e+83 3.1470e+85 1.9826e+87 1.2689e+89 8.2477e+90 5.4434e+92 3.6471e+94 2.4800e+96 1.7112e+98 1.1979e+100 8.5048e+101 6.1234e+103 4.4701e+105 3.3079e+107 2.4809e+109 1.8855e+111 1.4518e+113 1.1324e+115 8.9462e+116 7.1569e+118 5.7971e+120 4.7536e+122 3.9455e+124 3.3142e+126 2.8171e+128 2.4227e+130 2.1078e+132 1.8548e+134 1.6508e+136 1.4857e+138 1.3520e+140 1.2438e+142 1.1568e+144 1.0874e+146 1.0330e+148 9.9168e+149 9.6193e+151 9.4269e+153 9.3326e+155 9.3326e+157

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2021b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!