For loops
Fors are used when the number of iterations are known, i.e, if I want to repeat a code 10 times:
integer i
for i = 1 to 10
// The code
endfor
The variable "i" is called iterator. It assumes a new value for each repetition, for example, at first it assumes the value 1 and executes the code. When the block reaches its end, a new iteration begins and now "i" assumes the value of 2, and so on until the value of i surpasses the delimiter (in this case, 10).
While loops
While loops are used when the number of iterations are undetermined. It will repeat itself while its condition is true:
integer i = 1
while i < 10
// The block code
endwhile
Do/while loops
It's seemed with while loops except that the stop condition can appear in the beginning, middle or end of code block. Example:
integer i = 1
loop
// The block code
exitwhen i > 10
endloop
loop
exitwhen i == 0
// The block code
endloop
Answer mentally:
- What are loops?
- When we use for loops?
- When we use while loops?
- What's the difference between while and do/while loops?
No comments :
Post a Comment