Looping/Iterating
What
Repeating the same task
Doing the same thing across a data structure
for
/while
/do while
(imperative)
While
Format
need to ensure that loop is terminated
what the booleanExpression is for
Can make booleanExpression = true, and loop will be infinite
but have a
break
in the body to exit the loop
Do While
Format -
similar to while loop, but always does one execution of the body first.
For
Old/basic
Format -
Not good for functional style as initialization has mutated variable.
initialization can declared in the loop, and has scope just for the for loop.
Can declared outside of loop, initialized in loop and thus have scope inside nad outside of loop
If declared and init outside of loop, but reinit inside for loop, error will occur
Inifinite loop
for(;;) { // body }
All components in for loop are optional
Can have multiple initialization statements, booleanExpressions and updateStatements
Must have same data type in initialization
New/enhanced
aka for-each loop
-format
collection
must implement Iterable interface-
break statement
using a label (which is optional)
This will break out of the top level loop instead of inner loop where the break is set.
used in while/do while/switch/ for
continue statement
finishes the flow of the current loop.
Uses the same syntaz as that of break when using optional lables
used in while/do while/for
Recursion
stackoverflow exception
Nested loops
Links
for
while
do while
break, continue
Nested loops
other
Last updated
Was this helpful?