Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loop Structures.

Similar presentations


Presentation on theme: "Loop Structures."— Presentation transcript:

1 Loop Structures

2 Goals and Objectives while loop do-while loop for loop Infinite Loops
Nested Loops Counter Accumulator Sentential Value for each loop

3 Repetition Statements
Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: the while loop the do loop the for loop The programmer should choose the right kind of loop for the situation

4 4 Types of loops while (boolean condition)
do – while (boolean condition) for(initialization;condition;update) For each loop (Discussed later)

5 while Loop Executes a set of statements over and over again based on a condition. Pretest Loop Variable Loop Iteration – each execution of the loop. Example: while(condition) { <statements>; }

6 7/28/2018 8:39 PM The while Statement Loop structure that executes a set of statements as long as a condition is true The condition is a Boolean expression Will never execute if the condition is initially false The loop below iterates once because the condition is true and then continues to iterate until response is not 1: response = 1; while (response == 1) { System.out.print("Enter 1 or 0:"); response = input.nextInt(); } Refer to page 131 in the text.

7 3 parts of a while loop Initialization – (Priming the loop)
Terminating condition Updating statement Example: x = 0; // initialization while(x < 10) // x < 10 is the termination condition { x++; // increase x by 1 updating statement }

8 Logic of a while Loop condition evaluated false statement true

9 The while Statement An example of a while statement:
int count = 1; while (count <= 5) { System.out.println (count); count++; } If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times

10 The while Statement A loop can be used to maintain a running sum
A sentinel value is a special input value that represents the end of input A loop can also be used for input validation, making a program more robust

11 Trace a while loop final int LIMIT = 5; int count = 1;
while(count <= LIMIT) { System.out.println(count); count = count + 1; } System.out.println(“Done”); Output: 1 2 3 4 5 Done

12 do – while loop Alternative form of the while loop statement.
Not evaluated until after the first execution of the loop. Guarantee to execute once not like the other two loops. Post-test loop Variable loop Example: do { <statements>; } while(condition);

13 3 parts of a do while loop Initialization – (Priming the loop)
Terminating condition Updating statement Example: x = 0; // initialization do { x++; // increase x by 1 updating statement } while(x < 10); // x < 10 is the termination condition

14 The do-while Statement
7/28/2018 8:39 PM The do-while Statement Alternative form of the while statement Executes at least once The statement do { System.out.print("Enter 1 or 0:"); response = input.nextInt(); } while (response == 1); iterates once and continues to iterate until response is not 1. Refer to pages 131 and 132 in the text.

15 The do Statement A do statement has the following syntax: do {
} while ( condition ); The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false

16 Logic of a do Loop statement true condition evaluated false

17 The do Statement An example of a do loop:
int count = 0; do { count++; System.out.println (count); } while (count < 5); The body of a do loop executes at least once

18 Comparing while and do The while Loop The do Loop statement condition
true false condition evaluated The while Loop true condition evaluated statement false The do Loop

19 Example of a do – while loop
int count = 1; int limit = 5; do { System.out.println(count); count++; }while(count<limit); System.out.println(“Done”) Output: 1 2 3 4 Done

20 for loop A counter controlled repetition loop, works well when you know exactly how many times you want to execute the loop. Fixed Loop Pre-Test Loop

21 3 parts of a for loop Initialization Boolean condition Update Example:
for(initialization; boolean condition; update) { <statements>; }

22 7/28/2018 8:39 PM The for Statement Loop structure that executes a set of statements a fixed number of times Uses a loop control variable (lcv) The increment (++) or decrement (--) operators are used to change the value of the loop control variable The loop below executes until i is greater than 10: for (int i = 0; i <= 10; i++) { sum += i; } Refer to page 135 in the text.

23 The for Statement A for statement has the following syntax:
The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration

24 Logic of a for loop initialization condition evaluated false statement
true increment

25 The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }

26 The for Statement An example of a for loop:
for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times

27 The for Statement The increment section can perform any calculation
for (int num=100; num > 0; num -= 5) System.out.println (num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance

28 The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed

29 Example of a for loop int limit = 5;
for(int count = 1; count <limit; count++) { System.out.println(count); } System.out.println(“Done”);

30 Missing sections of a for loop
You can have sections of a for loop missing just as long as you have that section declared and initialized somewhere else. Semicolon still must appear between sections Example: for( ; x<5; x++) Or for( ; x < 5; )

31 Trace a for loop final int LIMIT = 5;
for(int count = 1; count<= LIMIT; count++) System.out.println(count); System.out.println(“Done”); OUTPUT: 1 2 3 4 5 Done Notice the for loop has no braces. Just like the if statement, it will only repeat the first statement only

32 Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely

33 Nested Loops How many times will the string "Here" be printed?
count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) System.out.println ("Here"); count2++; } count1++; 10 * 20 = 200

34 Nested Loops Loop that contains another loop in its body. Example:
for(int x = 0; x< 5; x++) { System.out.println(“Outer Loop”); for(int y = 0; y < 5; y++) System.out.println(“Inner Loop”); } It is very important to indent the inner loop Make sure you reset inner loop to reenter again.

35 Infinite Loops A loop that continues executing forever
7/28/2018 8:39 PM Infinite Loops A loop that continues executing forever Can be caused by syntax or logic errors. For example: while (num < 0) //error--no braces System.out.print("Enter a vale: "); num = input.nextInt(); Some errors can result in an overflow Refer to page 132 in the text. An infinite loop can cause an application to stop responding or just "hang". Closing the application window (with JCreator Pro) will end the application so that the source of the infinite loop can be located and corrected. Errors that result in an overflow may generate unexpected results rather than "hanging" the application.

36 Infinite Loops Loops where the boolean condition never becomes false.
Example int x = 0; while(x < = 5) { System.out.println(“Hello”); } x is never updated to become bigger than 5

37 Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally

38 Infinite Loops An example of an infinite loop:
int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } This loop will continue executing until interrupted (Control-C) or until an underflow error occurs

39 Accumulators, Counters, & Sentinel Values
Accumulator is a variable in a loop that keeps a running total or sum of a variable. Counter – is usually a variable increase by one to keep a record of how many times a loop has executed. Sentinel Value (Flag) – are inputted by the user to stop a loop. –999 or –1 Be careful not to add the sentinel value to the accumulator.

40 A variable that is incremented by a constant value
7/28/2018 8:39 PM Counters A variable that is incremented by a constant value Often used for counting loop iterations Should be initialized to 0 when declared The counter in the loop counts the number of responses: do { System.out.print("Enter 1 or 0:"); response = input.nextInt(); numResponses += 1; } while (response == 1); Refer to page 133 in the text.

41 Accumulators A variable that is incremented by a varying amount
7/28/2018 8:39 PM Accumulators A variable that is incremented by a varying amount Often used for summing Should be initialized to 0 when declared The accumulator in the loop sums values: do { System.out.print("Enter grade:"); grade = input.nextInt(); sumOfGrades += grade; } while (grade != 999); Refer to page 133 in the text.

42 7/28/2018 8:39 PM Using Flags A flag, or sentinel, indicates when a loop should stop iterating Often a constant Code is easier to modify when sentinels are constants declared at the beginning of an application A flag is used in the condition of the loop: final int STOP = 999; do { System.out.print("Enter grade:"); grade = input.nextInt(); sumOfGrades += grade; } while (grade != STOP); Refer to page 133 in the text.

43 Breaking out of a loop An if statement with the keyword break as a statement. When the if statement becomes true it will execute the break statement and take you out of that loop. If you have multiple nested loops the break will only break you out of the loop that it is located in.

44 Debugging Techniques The debugger included with many compilers
7/28/2018 8:39 PM Debugging Techniques The debugger included with many compilers Variable trace, which is a manual technique of list values of variables at the points of assignment Additional println() statements for displaying variable values at points of assignment "Commenting out" code to detect bugs through a process of elimination Refer to pages 136 and 137 in the text.

45 Using println() to Debug
7/28/2018 8:39 PM Using println() to Debug int num1 = 0; int num2 = 0; System.out.println("num1 before while: " + num1); //debug while (num1 < 10) { System.out.println("num1 in while: " + num1); //debug if (num1 % 3 == 0) { num2 += num1; System.out.println("num2: " + num2); //debug System.out.print(num2 + " "); } num1 += 1; } Refer to page 137 in the text. When using println() statements to debug a segment of code, it is usually most effective to place statements just after assignment changes the value of a variable.

46 Using Comments to Debug
7/28/2018 8:39 PM Using Comments to Debug int num1 = 0; int num2 = 0; while (num1 < 10) { //if (num1 % 3 == 0) { // num2 += num1; // System.out.print(num2 + " "); //} num1 += 1; } Refer to page 137 in the text. Comments can be used to comment out segments of code to determine through a process of elimination the location of any bugs.

47 7/28/2018 8:39 PM Variable Trace int num1 = 0; int num2 = 0; while (num1 < 10) { if (num1 % 3 == 0) { num2 += num1; System.out.print(num2 + " "); } num1 += 1; } Refer to page 136 in the text.

48 Iterators An iterator is an object that allows you to process a collection of items one at a time It lets you step through each item in turn and process it as needed An iterator object has a hasNext method that returns true if there is at least one more item to process The next method returns the next item Iterator objects are defined using the Iterator interface.

49 Iterators Several classes in the Java standard class library are iterators The Scanner class is an iterator the hasNext method returns true if there is more data to be scanned the next method returns the next scanned token as a string The Scanner class also has variations on the hasNext method for specific data types (such as hasNextInt)

50 Iterators The fact that a Scanner is an iterator is particularly helpful when reading input from a file Suppose we wanted to read and process a list of URLs stored in a file One scanner can be set up to read each line of the input until the end of the file is encountered Another scanner can be set up for each URL to process each part of the path

51 Iterators and for Loops
Recall that an iterator is an object that allows you to process each item in a collection A variant of the for loop simplifies the repetitive processing the items For example, if BookList is an iterator that manages Book objects, the following loop will print each book: for (Book myBook : BookList) System.out.println (myBook);

52 Iterators and for Loops
This style of for loop can be read "for each Book in BookList, …" Therefore the iterator version of the for loop is sometimes referred to as the for each loop It eliminates the need to call the hasNext and next methods explicitly It also will be helpful when processing arrays.

53 Common Errors Boolean condition never becoming false causing an infinite loop. Semicolon after a for or while loop Adding a sentinel value to an accumulator Missing semicolon after the while in a do – while loop. Forgetting to reset the inner loop to go back in.


Download ppt "Loop Structures."

Similar presentations


Ads by Google