Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming Loops

Similar presentations


Presentation on theme: "Java Programming Loops"— Presentation transcript:

1 Java Programming Loops
Phil Tayco San Jose City College Slide version 1.0 October 9, 2018

2 Loop Properties In the previous discussion, we introduced the structure of the while loop There are 3 types of loops used in Java – looking at the while loop structure we can see that there are characteristics of a loop that are also seen with the other 2 We’ll first look at the characteristics and then look to see how they are coded with the each loop structure

3 Loop Properties Scanner input = new Scanner(System.in); int counter = 0; double total = 0.0; while (counter < 5) { System.out.println(“Enter number: “); total += input.nextDouble(); counter++; } System.out.printf(“Average is %.2f\n”, total / 5); This program calculates the average of 5 numbers entered by the user It uses a while loop to calculate the total of all the numbers entered When the loop ends, the total is divided by 5 to print the average

4 Loop Properties Scanner input = new Scanner(System.in); int counter = 0; double total = 0.0; while (counter < 5) { System.out.println(“Enter number: “); total += input.nextDouble(); counter++; } System.out.printf(“Average is %.2f\n”, total / 5); First challenge is to determine what needs to repeat when the loop is executed This code represents the core design intent for using a loop Characteristic #1: Define the repeating code that is used inside the loop

5 Loop Properties Scanner input = new Scanner(System.in); int counter = 0; double total = 0.0; while (counter < 5) { System.out.println(“Enter number: “); total += input.nextDouble(); counter++; } System.out.printf(“Average is %.2f\n”, total / 5); One of the key elements of the loop that also pop out is the use of the counter variable counter appears inside and outside the loop and is applied in 3 different ways Its usage is essentially acting as a variable that controls the execution of the loop

6 Loop Properties The first use of counter is before the loops starts
Scanner input = new Scanner(System.in); int counter = 0; double total = 0.0; while (counter < 5) { System.out.println(“Enter number: “); total += input.nextDouble(); counter++; } System.out.printf(“Average is %.2f\n”, total / 5); The first use of counter is before the loops starts Here, counter is initialized to a value of 0 Characteristic #2: Declare and initialize the loop control variable

7 Loop Properties The 2nd use of counter is in a relational expression
Scanner input = new Scanner(System.in); int counter = 0; double total = 0.0; while (counter < 5) { System.out.println(“Enter number: “); total += input.nextDouble(); counter++; } System.out.printf(“Average is %.2f\n”, total / 5); The 2nd use of counter is in a relational expression The resulting of the expression is the key to how often a loop will repeat Characteristic #3: Test the control variable in an expression to determine whether or not the loop continues

8 Loop Properties Scanner input = new Scanner(System.in); int counter = 0; double total = 0.0; while (counter < 5) { System.out.println(“Enter number: “); total += input.nextDouble(); counter++; } System.out.printf(“Average is %.2f\n”, total / 5); The 3rd use of counter is in the loop, adding one to counter Another way to look at it is that we are updating the value of counter Characteristic #4: Update the control variable in the loop to help ensure the loop eventually ends

9 Loop Properties These 4 characteristics make up the logical components of all loops Define the sequence of code that you want to repeat Establish and initialize a loop control variable Define an expression that uses the control variable to determine how the loop repeats and ends Update the value of the control variable inside the loop All programming languages that structure code that repeats have these characteristics How the language defines them is essentially a matter of syntax

10 Do…while Loop The 2nd type of loop is the do…while loop
Scanner input = new Scanner(System.in); int counter = 0; double total = 0.0; do { System.out.println(“Enter number: “); total += input.nextDouble(); counter++; } while (counter < 5); System.out.printf(“Average is %.2f\n”, total / 5); The 2nd type of loop is the do…while loop Structurally, the code is similar to the while loop with the main difference in the location of the loop evaluation expression This loop example produces the same result as the previous one

11 Do…while Loop We can see the loop properties in action here
Scanner input = new Scanner(System.in); int counter = 0; double total = 0.0; do { System.out.println(“Enter number: “); total += input.nextDouble(); counter++; } while (counter < 5); System.out.printf(“Average is %.2f\n”, total / 5); We can see the loop properties in action here Define the sequence of code that you want to repeat Establish and initialize a loop control variable Define an expression that uses the control variable to determine how the loop repeats and ends Update the value of the control variable inside the loop

12 Comparing Loops Comparing while and do…while in this instance leads to questions about them What’s the difference between the loops? When do I use one or the other? The main difference structurally is the location of the loop control variable evaluation The while loop evaluates control before going in the loop The do…while evaluates control at the end of the loop The evaluation timing has a key logical impact Theoretically, it’s possible for the while loop to evaluate control as false on the first test

13 Comparing Loops Scanner input = new Scanner(System.in); int counter = 0; System.out.println(“Enter limit”); int limit = input.nextInt(); double total = 0.0; while (counter < limit) { System.out.println(“Enter number: “); total += input.nextDouble(); counter++; } System.out.printf(“Average is %.2f\n”, total / limit); In this example, the “limit” variable is created to allow for a varying amount of numbers entered by the user to total and calculate an average In most situations, the limit value will be number greater than 0 If the user enters zero, the loop wouldn’t even start (in fact, an error will occur after the loop…)

14 Comparing Loops In this example, we could check the value entered by the user for limit to ensure it is greater than 0 before the loop starts counter and limit together make up the control variables so in this manner, they are being initialized properly for the loop This is necessary because of the possibility that any while loop may not start in the first place Given this, you could design a loop with a legitimate possibility that it may not start at all Conversely, because do…while evaluates the control variable at the end of the loop, this guarantees the body of the loop is executed at least once

15 Comparing Loops Scanner input = new Scanner(System.in); int limit; do { System.out.println(“Enter limit”); limit = input.nextInt(); } while (limit <= 0); The do…while shows all 4 loop characteristics using limit as the control variable The logic of the loop is such that we repeat asking the user to for a limit value until they enter a value greater than 0 This loop ensures the limit entered by the user is greater than 0 and will also ask the user for that value at least once Notice that the limit variable is not initialized – this is okay because the limit value is set within the loop (and the loop is guaranteed by rule to execute at least once) This could still be done with a while loop too…

16 Comparing Loops Scanner input = new Scanner(System.in); int limit = 0; while (limit <= 0) { System.out.println(“Enter limit”); limit = input.nextInt(); } Logically, this works as well, but in order to ensure the loop executes at least once, the limit variable must first be initialized properly The effect is the same as the do…while, but the logic of the code implies that do…while flows more naturally Ultimately, it’s a matter of style – one loop structure does not significantly perform faster than the other Understand the loop properties and structural difference between the loops to develop your coding preference Let’s now go back to the original average calculation program to look at the 3rd type of loop

17 The for Loop Scanner input = new Scanner(System.in); double total = 0.0; for (int counter = 0; counter < 5; counter++) { System.out.println(“Enter number: “); total += input.nextDouble(); } System.out.printf(“Average is %.2f\n”, total / 5); The for loop is the 3rd type of loop that essentially captures 3 properties of a loop in one line of code The loop can essentially be read as “repeat the following 5 times” More specifically, the line of code can be read as “for each counter value from 0 to less than 5 incrementing counter by 1, repeat some code”

18 The for Loop Like before, we can see the loop properties here
Scanner input = new Scanner(System.in); double total = 0.0; for (int counter = 0; counter < 5; counter++) { System.out.println(“Enter number: “); total += input.nextDouble(); } System.out.printf(“Average is %.2f\n”, total / 5); Like before, we can see the loop properties here Define the sequence of code that you want to repeat Establish and initialize a loop control variable Define an expression that uses the control variable to determine how the loop repeats and ends Update the value of the control variable inside the loop The for loop line of code implies that it is one statement, but it actually defines a sequence of actions

19 The for Loop A full breakdown of the “for” sequence is:
Scanner input = new Scanner(System.in); double total = 0.0; for (int counter = 0; counter < 5; counter++) { System.out.println(“Enter number: “); total += input.nextDouble(); } System.out.printf(“Average is %.2f\n”, total / 5); A full breakdown of the “for” sequence is: Initialize counter as an integer to 0 If counter is less than 5, execute the loop body, if not, the loop ends When the body is complete, add one to counter and go back to step 2

20 Comparing Loops As before when comparing the while and do…while loops, the same questions come up What are differences between these loops? When do I use one or the other? The fact that the for loop generates the same result as the while loop (as well as the do…while loop) suggests that they are interchangeable This is ultimately a true statement, but like do…while vs. while, the for loop has a tendency to be used in certain logical flow situations Looking at the for line of code, the natural read establishes the limits of the loop up front “int counter = 0” sets a starting point “counter < 5” expresses the stopping point This makes the first part of the for line read as “from 0 to 4”

21 Comparing Loops Moreover, the “counter++” adds to the read by specifying how to get “from 0 to 4” A more accurate read of the line then is “from 0 to 4 in increments of 1, repeat the loop body” Because of this, for loops tend to be used in situations where counting is involved In particular, if a sequence of code is naturally expressed to repeat a certain number of times, the for loop tends to be favored Logically, for can still be used in any loop situation Let’s go back to the do…while loop example

22 Comparing Loops Scanner input = new Scanner(System.in); for (int limit = 0; limit <= 0; ) { System.out.println(“Enter limit”); limit = input.nextInt(); } The logical effect of the loop is the same as the do…while here in that it repeats until the user enters a number greater than 0 Reading the for line here would be “from limit starting at 0 to as long as it is less than or equal to 0, repeat asking the user for a value for limit” Notice there is no 3rd part of the loop as well – normally this is where the loop control variable is updated (counter++) – no code is needed here since limit is updated within the loop While this can work, the while or do…while loops are more natural There is also a problem with this particular loop

23 Comparing Loops Scanner input = new Scanner(System.in); for (int limit = 0; limit <= 0; ) { System.out.println(“Enter limit”); limit = input.nextInt(); } The “limit” control variable is initialized as part of the for loop With for loops, when the control variable is defined within the “for ()”, its lifetime lasts as long as the loop continues Once the loop ends, this and all variables declared within the loop go away Here, while the for loop structure is logically correct, the use of limit after the loop ends is gone To fix this in this example, limit must be declared first outside the loop, making the initialization at the beginning of for unnecessary as well

24 Comparing Loops Scanner input = new Scanner(System.in); int limit = 0; for (; limit <= 0; ) { System.out.println(“Enter limit”); limit = input.nextInt(); } limit can now be used after the for loop is done, and will also contain the value the user entered The “;”s are needed in the for loop line to delimit the 3 parts of the loop This shows there are ways to make each loop work to produce the same logical results Notice here that in getting the for loop to work, it ends up looking like a while loop! Ultimately, it’s a matter of style, but there are guidelines that suggest when to use which loop The guidelines are based 2 loop control types

25 Comparing Loops “Counter-based” loops are those where repeating the loop body is controlled by counting values in a specific range They tend to be read as “from x to y” and “for each z” and suggest use of the for loop “Sentinel-based” loops are those where repeating the loop body is controlled by a variable’s state They tend to be read with “as long as x is true” and “do y until z” and suggest use of the while or do…while loop while and do…while are closely related and are distinguished by whether or not you want to guarantee at least one iteration of the loop body Developing an intuitive sense of which loops to use when comes with practice

26 Combinations Scanner input = new Scanner(System.in); int limit = 0; do { System.out.println(“Enter limit”); limit = input.nextInt(); if (limit <= 0) System.out.println(“Limit must be > 0”); } while (limit <= 0); This example adds some an error message as an indicator to the user to retry entering a value for limit While not absolutely necessary to do so, it can be seen as a user friendly interaction with the user It also shows how the sequence of code in the loop body can contain other types of structures (selection statements as well as other loops) – we will see more examples and ways on how to design combinations of code to reach a solution

27 Programming Exercise 4 Write a program that finds all the prime numbers from 1 to a number entered by the user If the number it is examining is prime, it prints it out to the user, otherwise it simply goes to the next number A prime number is a number that is only divisible by 1 and itself For example, if the user enters a maximum number as 20, the program examines each integer from 1 to 20 The prime number results printed will be 1, 2, 3, 5, 7, 11, 13, 17, 19 Remember the top-down design approach discussed in the previous module and see if you can use it here to develop your solution Hint: This solution will require “nested” loops which is a loop that will contain another loop


Download ppt "Java Programming Loops"

Similar presentations


Ads by Google