sheng/passwords

From CDS 130

Jump to: navigation, search

1. While-loop

Similar to the for loop, the while can be used to iteration.

while (test)
 Execute these commands
end


Means if the statement of test is correct (true) then execute the commands between the while and end. These two programs are equivalent:

i = 1;
while (i < 3)
  i = i+1;
  Do Something
end


for i = [1,2]
  Do Something
end


A while loop can be unrolled:

i = 1;
if (i < 3)
  i = i+1;
  Do Something
end
if (i < 3)
 i = i+1;
 Do Something
end


2. Break

The break statement

For some problems, you will not want to write a program that always executes every iteration in a for loop. For example, suppose that you are told to execute the following program and that you know that the value of z will always be assigned to be a zero or one because the function isspecial only specifies a zero or one.

g = 3;
for i = [1:100]
  z = isspecial(g);
  if (z == 1)
     DO SOMETHING
  end
end
MORE COMMANDS

If you think about how this program works, you will realize that once z was assigned the value of one and DO SOMETHING is executed no more iterations are needed because DO SOMETHING will never be executed again.

g = 3;
for i = [1:100]
  z = isspecial(g);
  if (z == 1)
     DO SOMETHING
     break;
  end
end
MORE COMMANDS

If you add a break statement right after DO SOMETHING, you indicate that once DO SOMETHING is executed, then no more iterations are needed - the program can just jump (or "break out of the loop") to the line that says MORE COMMANDS.

Personal tools