Home Advanced loops

Advanced loops

In CSE 142, we learned two basic looping constructs: for loops and while loops. In CSE 143, we learn about more advanced looping constructs such as Iterators (which must be used in combination with some other looping technique) and foreach loops.

Iterators

Use iterators when you want to use a foreach loop, but also want to simultaneously modify the collection you are iterating over. Prefer using foreach loops whenever possible.

Foreach loops

Use a foreach loop when you want to iterate over some sort of collection such as an array or a list, and work on the collection one element at a time. Prefer using foreach loops over for loops and manually manipulating Iterators whenever possible.

Recursion

Use recursion when none of the above appear to be a good fit when looping, and when simple iteration will not suffice. For example, recursion is often a good fit when dealing with branching data structures such as trees.

Higher-order functions

Do not use higher-order functions (streams, lambdas, map, etc).