Loop Basics

It is often necessary to repeat certain blocks of code for a specified(or unspecified) number of times. We use a control structure known as a loop to accomplish this. Every loop has four basic parts:
  1. Loop control variable declaration/initialization
  2. Loop condition
  3. Control variable alteration/reassignment
  4. Loop body(statements to be repeated)

Loops come in two basic varieties. In PreTest Loops, he condition is tested before the loop execute. This means that if the condition fails, the code in the loop may never execute. The other variety of a PostTest Loop. In these types of loops, the condition is tested after the loop code runs. The code will always run at least once.

Regardless of whether you loop is pre or post test, it also has another type of classification: counting or sentinal. Counting loops are set to execute a certain number of times. Loops that depend on user input are called sentinal loops, and will execute as many times as necessary until the user enters a predefined value.

Finally, Java has two loop keywords that can help control the flow of the loop. Those words are ’break’ and ‘continue.’ Break will immediately send control to the code following the loop. Continue sends control to the top of the loop.

While Loops

A while loop is a pretest iterative structure that can be used as a counting or sentinal loop. In general, a while loop looks like this: <control var intitialization> while(<loop condition>) { <loop body> <control var alteration> }
As a sentinal loop, we replace the var init with a user prompt. This is called a priming read. We also then replace the var alteration with the same prompt. The loop below asks the user to enter an unknown amount of numbers. Input will terminate when they enter -1. int input=reader.readInt("Enter a number (-1 to quit)"); while(!(input==-1)){ input=reader.readInt("Enter a number (-1 to quit)"); } ...<more code to deal with input>