4th Algo Class

Repetition

An operation that is used to repeat one or more instructions until the condition to stop applies. The number of repetition can also be predefined by an amount or defined by a user later at run-time.

Operations:

  • For, gives a condition for the initial expression where once the condition expression is invalid then the repetition will stop. There is a third expression in For where it is an increment/decrement of the initial expression so that it won’t loop forever. A nested loop can be created with For by making a loop within a loop where the repetition starts from the inner side.
  • While, gives a condition (Boolean expression) and when it is true then it will run a statement and loop to the condition again until the condition is false. If the condition is false from the start then the statements inside the while operation will never be executed.
  • Do-While, does the statement first and then checks the condition after doing all statements within Do, if the condition is still true then it will keep repeating the statements in Do. Once again, the repetition will stop once the condition is false. Unlike While, if the condition is false from the start, it will execute the statements within Do at least once.

You could also end repetitions with

  • Sentinel, a restriction. Say that you’re not allowed to enter a value outside of 0 < x < 10 and your input was 17, then a repetition will occur.
  • Question, an option. Say that at the end of a program you are asked whether you want to continue or not, by inputting a specific answer (YES / NO) then it will repeat the statements again.

 

Break & Continue

Break is used to force finish a loop, when it is run it will jump out of the block of statements and end the repetition. It can also be used to end the Switch operation.

Continue is used to skip the statement block once when a certain condition applies and then continues the repetition again until the looping ends.

Leave a Reply

Your email address will not be published. Required fields are marked *