Repe$$on CSC 121 Fall 2015 Howard Rosenthal
Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while for Learn nested looping Learn how to use break statements to exit a loop Begin to learn how to deal with situations where faulty or out of range input is supplied 2
Introduc$on to Loops Many of the tasks performed by computers require repetition, often massive repetition Using repetitive syntax can make your code more concise and easier to write and debug Java has three types of repetitive constructs (also known as loops): while; dowhile; or for Loops are built out of several fundamental statements because there are three things (in each of the three types of loops) that must be done correctly: The loop must be initialized correctly. The ending condition must be tested correctly. The body of the loop must change the condition that is tested. Overlooking one of these aspects results in a defective loop and a sometimes difficult to find program bug! Usually each of these three considerations is located in a different spot. No wonder that loops often go wrong! You have to plan out the logic of your program in order to effectively use loops and conditionals 3
Types of Loops type counting loop sentinel-controlled loop result-controlled loop description Uses a loop control variable to count upwards or downwards (usually by an integer increment.) Loop keeps going until a special value is encountered in the data. Loop keeps going until a test determines that the desired result has been achieved. 4
The while Statement Here is a program with a loop. It contains a while statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a while loop public class LoopExample public static void main (String[] args ) // start count out at one int count = 1; while ( count <= 3 ) System.out.println( "count is:" + count ); count = count + 1; // add one to count System.out.println( "Done with the loop" ); 5
The Basic Syntax of the while Statement while (condition) statement 1; statement 2; o 0 o statement n; You execute through the entire block repetitively until the condition is false unless you encounter a break statement The break will typically occur based on a separate condition tested with an if statement 6
Basic Terminology of the while Statement The condition is a Boolean expression: something that evaluates to true or false. The condition can be complicated, using many relational operators and logical operators. A single statement is allowed Without braces only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body. If one of the statements in the while block doesn t eventually change the value of the condition then the loop goes on forever. The while loop may not be executed at all if the initial condition is false There is not a semi-colon after the while statement. If you put one there you will end the loop before it executes anything 7
Counters can be decremented rather than incremented Here is a program with a loop. It contains a while statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a while loop decrementing public class WhileLoopExample public static void main (String[] args ) int count = 2; // count is initialized while ( count >= 0 ) // count is tested System.out.println( "count is:" + count ); count = count - 1; // count is changed by -1 System.out.println( "Done counting down." ); 8
The do-while Statement Here is a program with a loop. It contains a do statement, followed by a block of code, followed by a while statement. // Example of a do-while loop public class DoWhileExample public static void main (String[] args ) int count = 1000; // initialize do System.out.println( count ); count++ ; // change s after the entire block is executed while ( count < 10 ); // test System.out.println( "Done with the loop" ); 9
The Basic Syntax of the do-while Statement do statement1; statement2; o 0 0 statementn; while (condition); 10
Basic Terminology of the do-while Statement The condition is a Boolean expression: something that evaluates to true or false. The condition can be complicated, using many relational operators and logical operators. A single statement is allowed Without braces to create a block only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body. The do-while is always executed at least once, if the do statement is executed There is a semi-colon after the while statement in a dowhile 11
The for Statement Here is a program with a loop. It contains a for statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a for loop public class ForExample public static void main (String[] args ) int sum=0; for ( int count = 0; count <= 5; count++ ) sum = sum + count ; System.out.print( count + " " ); System.out.println( \nsum is: " + sum ); Initialization count = 0 loop condition count <= 5 sum = sum + count Print count count++ Print sum false 12
The Basic Syntax of the for Statement for (initialization; loop condition; update statements) statement1; statement2; o 0 0 statementn; 13
Basic Terminology of the for Statement initialization Used to initialize basic variables used in the loop condition More than one variable can be set, separated by commas You can declare the variable in the for statement, but then it is only valid within the for loop that it is created for for (int j=3, k=4; ; ) If no variables are set, you must have a ; before the loop condition this typically means that the variable has been set prior to the for statement The initialization portion of the for statement is only executed once, each time you enter the loop loop condition A boolean expression evaluates as true or false Evaluated at the beginning of each loop Although this statement can be left out, leaving it out could lead to an infinite do loop, unless you execute a break statement inside the loop 14
Basic Terminology of the for Statement (2) update statement(s) Increases or decreases a value, typically one or more used in the loop condition Should always executed at the end of the loop body that s why we use postfix Can include more than one statement, separated by commas for( ; ; i++, j= j+5) Notes: If you are eliminating multiple parts of a for statement it may be better to use a while or do-while Don t stuff too many extraneous things into the for statement, you ll confuse yourself 15
Nested Loops A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop. Of course, they can be the same kind of loops too. Inner loops always stay completely inside their outer loops An inner loop may be skipped over during the execution of an outer loop For instance, if the loop is inside of an if block that isn t executed, then that loop wouldn t be executed 16
Nested Loop Example // Example of nested loop public class NestedLoops public static void main (String[] args ) int height =5; int width = 4; for ( int i = 0 ; i < height ; i++ ) for ( int j = 0 ; j< width ; j++ ) System.out.print( "*" ) ; System.out.println( "" ) ; Now let s look at the MultTable Example 17
The break statement Used to exit the innermost loop that the break is found within, unless the loop is labeled Loop is labeled with looplabelname: followed by the loop Next statement executed is the first statement beyond the scope of that loop If you label a loop the break statement can be used to exit through an outer nesting We ll look at BreakLabeledLoop.java 18
The flag or sendnel A flag or sentinel is a value appended to a data collection that signals the end of the data. The idea of a sentinel controlled loop is that there is a special value (the sentinel) that is used to control when the loop is done. In following code fragment, the user enters a zero when the sum is complete. Zero is the sentinel. Here is how the program should work import java.util.scanner; // Add up integers entered by the user. // After the last integer, the user enters a 0. class AddUpNumbers public static void main (String[] args ) Scanner keyboard = new Scanner( System.in ); int value, sum = 0; System.out.print( "Enter first integer (enter 0 to quit): " ); value = keyboard.nextint(); //we initialize value before entering the loop while ( value!= 0 ) sum = sum + value; System.out.print( "Enter next integer (enter 0 to quit): " ); value = keyboard.nextint(); //update value inside the loop System.out.println( "Sum of the integers: " + sum ); 19
Bad Input data There are cases when erroneous data is entered There are many options Request revised data Exit the program In order to do either you must check the data first Note: Some inputs will cause the program to crash Can you name 0ne? We will look at GeneralAverage in a few minutes 20
Scope of a Variable (1) A variable s scope is determined by the highest level of braces within which it is defined. It works at that level and all nested level If you use the same variable name in an outer and nested blocks, an error will occur. If you exit a block where a variable is defined you can reuse the variable name It s values are separate from the originally named variable Don t use the same variable name twice in a program it only confuses things. You are allowed to continuously redeclare a variable in the same statement with a loop Scope is extremely important to understand in nested loops. Once you leave the loop a variable declared in the loop no longer exists. 21
Scope of a Variable (2) / Demonstrate block scope. class Scope public static void main(string args[]) int n1; // Visible in main n1 = 10; if(n1 == 10) // start new scope int n2 = 20; // visible only to this block // n1 and n2 both visible here. System.out.println("n1 and n2 : "+ n1 +""+ n2); // n2 = 100; // Error! n2 not known here // n1 is still visible here. System.out.println("n1 is " + n1); 22
Scope of a Variable (3) class LifeTime public static void main(string args[]) int i; for(i = 0; i < 3; i++) int y = -1; System.out.println("y is : " + y); Variable y is declared inside for loop block. Each time when control goes inside For loop Block, Variable is declared and used in loop. When control goes out of the for loop then the variable becomes inaccessible. 23
Scope of a Variable (4) class ScopeInvalid public static void main(string args[]) int num = 1; // creates a new scope int num = 2; // Compile-time error // num already defined class ScopeValid public static void main(string args[]) // creates a new scope int num = 1; // creates a new scope int num = 2; 24
Programming Exercises Class (1) Exercise 2 Pictures Write a program that reads an integer n and prints the following right triangle with base and height n 1 x 2 xx 3 xxx 4.. n xxxxxx.x 25
Programming Exercises Class(2) Exercise 9 GeneralAverage Write a program that calculates the average of n test scores, such that each score is an integer in the range 0 to 100. Your program should first prompt for an integer n and then request n scores. Your program should also test for invalid data. If a user enters a number outside the correct range, the program should prompt for another value. Round the average to the closest integer. 26
Programming Exercises Lab (1) Exercise 3 MorePictures Write a program that accepts an integer n and prints out the following picture of a diamond with 2n-1 rows 1 X 2 X X X 3 X X X X X n XXXXXXXXXXX (2n-1 times). 2n-1 X 27
Programming Exercises Lab (2) Exercise 10 Modified Average Write a program that accepts a list of n test scores, and then finds the average of the n-1 highest scores on the list that is, the lowest score on the list is not included in the average. For example, if the test scores are 90, 80, 70, and 60, the average is computed as (90 + 80+70)/3. The low score of 60 is excluded Your program should first prompt for an integer n and then request n scores. Your program should also test for invalid data. If a user enters a number outside the correct range, the program should prompt for another value. Round the average to the closest integer. 28