Skip to main content
Logo image

Section 7.8 The while loop

MATLAB also has a while loop whose syntax is given here:
while expression      % use when number of loop iterations
    command           % is not necessarily known
    command
    ...
end
MATLAB can handle factorials of really large numbers quite easily. Here is code using a while loop that determines the first integer n whose factorial has at least 100 decimal places:
n = 1;
fact = 1;
while fact < 1e100
   n = n + 1;
   fact = fact * n;
end
fprintf('%d! = %g\n', n, fact)
Running this code yields:
70! = 1.19786e+100
There is no do-while loop as there is in C. So the only two types of loops are the for loop and the while loop. Fewer choices to make!