using nested for loop to print all of factorial
52 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!