Factorial using a for loop

33 Ansichten (letzte 30 Tage)
Kayla
Kayla am 19 Nov. 2022
Beantwortet: Walter Roberson am 19 Nov. 2022
Hello, I looked at the other questions answered but they were not helpful for what I am trying to figure out. I have played around with different ways to write this but I cant figure it out. I was given no background information into how to go about this. I have seen people answer the question regarding a "while" loop and that makes complete sense, but the "for" loop is stumping me. I have been trying for three days now. I am also including a screen snip of the exact question being asked.
n=4
for i=1:n
x=n*(n-1);
end
disp('The value of factorial of 4 is')
disp(x)
  1 Kommentar
Kayla
Kayla am 19 Nov. 2022
I figured it out. Im leaving this up incase it helps anyone else in the future. I still havent figured out how to display the text along with the value of n and x but this code worked as you change the value of n.
n=4
x=1;
for i=1:n
x=x*i;
end

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Walter Roberson
Walter Roberson am 19 Nov. 2022
iteration 1, i=1, output is 1=1, =1*i
iteration 2, i=2, output is 1*2=2, =1*i
iteration 3, i=3, output is (1*2)*3=2*3=6, =2*i
iteration 4, i=4, output is (1*2*3)*4=6*4=24, =6*i
So at iteration i, the output is the previous output times i

Kategorien

Mehr zu Entering Commands finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by