loops - Loops Why a Loop This section will discuss three...

Info icon This preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Loops Why a Loop? This section will discuss three different kinds of loops in Java. Loops are structures that repeat the same set of actions over and over until a specified condition becomes false. To see why loops are useful, suppose we want to print the sum of 100 numbers entered by the user. With what we’ve seen so far, we’d have to write 100 separate prompts and input statements – this would be a big mess. Really, for each number we want to do exactly the same thing – print a prompt and read in the number. With a loop, we can repeat these two steps a certain number of times without having to write each one out separately. While Loops The easiest kind of loop is a while loop . This loop executes a set of instructions repeatedly until a given condition becomes false. Syntax Here is the syntax for a while loop: while (condition) { //statements } The condition is evaluated before anything inside the loop is executed. If the condition is false, we immediately skip to the code after the loop. If the condition is true, we execute the statements inside the loop, and then check the condition again. If the condition is false, we leave the loop. If it is still true, we execute the loop again. We repeat this process until the condition becomes false. Examples Here is how we can use a while loop to print the sum of 100 numbers entered by the user: //keep track of the sum of the elements we’ve seen so far int sum = 0; //keep track of how many elements we’ve asked for int count = 0; //keep looping while we haven’t asked for 100 elements Scanner s = new Scanner(System.in); while (count < 100) { //ask for the next number System.out.print(“Enter a number: “);
Image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon