While-loops vs for-loops
You have seen both forms of loops in class and in the early sections of Chapter 6 of the text. In Java, the two forms of loops are (technically) almost interchangeable. So when would you prefer one over the other?For-loops are normally used for iterating over a known sequence of values
Examples:- examining all the characters of a string
- repeating an action a fixed number of times
- iterating over the elements of an array or list
While-loops are normally used when the number of iterations is difficult to determine in advance
Examples:- reading or parsing input
- searching for the next largest prime number
- iteratively repeating a calculation until successive results are sufficiently close