using nested for loop to print all of factorial
47 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
DGM
il 16 Giu 2022
Modificato: DGM
il 16 Giu 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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!