0% found this document useful (0 votes)
4 views7 pages

Loops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

Loops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

MATLAB

FOR & WHILE LOOPS


FOR LOOPS

• Used when the number of passes is known ahead of time


for loop variable = m:s:n
statements
end

• A simple example of a for loop is

for k = 5:10:35
x = k^2
end

• Note: k takes on the values 5, 15, 25, and 35, and x takes on the values
25, 225, 625, and 1225.

• The program then continues to execute any statements following the end
statement.
FLOWCHART OF A FOR LOOP.
NOTES ON LOOP VARIABLE EXPRESSION
K = M:S:N

• The step value s may be negative.

• If s is omitted, the step value defaults to 1.

• If s is positive, the loop will not be executed if m is


greater than n.

• If s is negative, the loop will not be executed if m is


less than n.

• If m equals n, the loop will be executed only once.


WHILE LOOPS

• The while loop is used when the looping process


terminates because a specified condition is satisfied,
and thus the number of passes is not known in advance.
• A simple example of a while loop is
x = 5;
while x < 25
disp(x)
x = 2*x -1;
end

• The results displayed by the disp statement are 5, 9, and


17
THE TYPICAL STRUCTURE OF A WHILE
LOOP
while logical expression
statements
end

For the while loop to function properly, the following


two conditions must occur :
1. The loop variable must have a value before the
while statement is executed.
2. The loop variable must be changed somehow by
the statements.
FLOWCHART OF A FOR WHILE.

You might also like