Download presentation
Presentation is loading. Please wait.
1
ITM352 Loops Lecture #6
2
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Lab class dates have changed!!! m Check the “Weekly Schedule” for details m Go to E 102, NOT this classroom!!! r Listserv (ITM352-L) m All class announcements will go out on this list (not via my mail alias anymore) m Hints, answers to questions (non-personal), etc. r Quizzes were terrible… m I’m going to drop this one for everyone m We’ll try again soon… m Need to re-think class structure
3
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 3 ** Important Notice ** r Section 2 m On 2/4, 2/6, 2/11 please go to the section 1 lecture from 12:00-1:15pm, there will be no 1:30-2:45pm lecture on those dates m If you absolutely cannot make these lectures, come see me RIGHT AWAY
4
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 4 Today r Quiz answers r What’s the problem here? m New class schedule r Review m Documentation and Coding Style m Control Flow m Conditionals (decisions) r New topic m Loops r Review of previous material m You ask, I answer
5
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 5 Quiz #1 Answers Name: __Prof. Port_________ ID #: ____123-45-678_______ 1) Write a Java statement that declares a variable of type float named birthYear and initialize it with the year of your birth (explicitly cast your birth year value appropriately) float birthYear = (float) 1966; 2) Write out a complete Java program (with class definition, main method, comments, proper coding style, etc.) that prints “I was born in the year” and concatenates it with the variable birthYear class PrintBirthYear { float birthYear = (float) 1966; public static void main (String args[]) { System.out.println(“I was born in the year” + birthYear); } 3)Write a compound conditional expression with a type boolean return value of true when a string lastName is your last name and birthYear is greater or equal to 1982. lastName.equals(“Port”) && (birthYear >= 1982) // You can buy beer!
6
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 6 What’s The Problem? r Is the material too obscure? r Presentation to fast? r Class too unorganized? r Not interesting? r What suggestions do you have that might help? r Be responsible! m When you are confused or need help ** seek help ** m Do not put things off! m Read through the assigned sections of the book BEFORE lecture m If you have a problem, come see me BEFORE it becomes an un- fixable problem.
7
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 7 New Class Schedule
8
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 8 Review
9
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 9 Documentation and Style r Use meaningful names for variables, classes, etc. r Use indentation and line spacing as shown in the examples in the text r Always include a “prologue” (an brief explanation of the program at the beginning of the file) Use all lower case for variables, except capitalize internal words ( eggsPerBasket ) Use all upper case for variables that have a constant value, PI for the value of pi (3.14159…) (see text for more examples)
10
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 10 Indentation r Codes inside a block should be indented. r Indent 2 to 4 spaces r Be consistent.
11
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 11 Named Constants r Named constant—using a name instead of a value Example: use TAX_RATE instead of 5.25 r Advantages of using named constants m Easier to understand program because reader can tell how the value is being used m Easier to modify program because value can be changed in one place (the definition) instead of being changed everywhere in the program. m Avoids mistake of changing same value used for a different purpose
12
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 12 Defining Named Constants public —has public visibility. There are no restrictions on where this name can be used static —must be included, but explanation has to wait final —the program is not allowed to change the value r The remainder of the definition is similar to a variable declaration and gives the type, name, and initial value. r A declaration like this is usually at the beginning of the file and is not inside the main method definition. public static final double PI = 3.14159;
13
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 13 What is “Flow of Control”? r Flow of Control is the execution order of instructions in a program r All programs can be written with three control flow elements: 1. Sequence - just go to the next instruction 2. Selection - a choice of at least two r either go to the next instruction r or jump to some other instruction 3. Repetition - a loop (repeat a block of code) at the end of the loop r either go back and repeat the block of code r or continue with the next instruction after the block r Selection and Repetition are called Branching since these are branch points in the flow of control
14
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 14 Java Flow Control Statements Sequence r the default r Java automatically executes the next instruction unless you use a branching statement Branching: Selection r if r if-else r if-else if-else if- … - else r switch Branching: Repetition r while r do-while r for
15
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 15 Boolean Expressions r Boolean expressions can be thought of as test conditions (questions) that are either true or false r Often two values are compared r For example: Is A greater than B? Is A equal to B? Is A less than or equal to B? etc. r A and B can be any data type (or class), but they should be the same data type (or class)
16
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 16 Java Comparison Operators
17
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 17 Comparing objects r Great care must be taken when comparing objects: Statements like myRobot == theRobot compare references to where the objects are stored, not the objects themselves! m In general the equals() method is used r The objects themselves define what it means for objects to be equal myRobottheRobot myRobot == theRobot is false aRobot theRobot == aRobot is true
18
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 18 Example: Comparison Methods for String Class r “==“ does not do what you may think for String objects m When “==“ is used to test objects (such as String objects) it tests to see if the storage addresses of the two objects are the same r are they stored in the same location? r more will be said about this later r Use “.equals” method to test if the strings, themselves, are equal String s1 = “Mondo”; String s2; s2 = SavitchIn.readLine(); //s1.equals(s2) returns true if the user enters Mondo, false otherwise .equals() is case sensitive Use.equalsIgnoreCase() to ignore case
19
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 19 Compound Boolean Expressions Use && to AND two or more conditions Use || to OR two or more conditions r See text for definitions of AND and OR r For example, write a test to see if B is either 0 or between the values of A and C : (B == 0) || (A <= B && B < C) r In this example the parentheses are not required but are added for clarity m See text (and later slides) for Precedence rules m Note the short-circuit, or lazy, evaluation rules in text (and later in slides) Use a single & for AND and a single | for OR to avoid short- circuit evaluation and force complete evaluation of a boolean expression
20
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 20 if-else if-else if-…- else Example if(score >= 90 && score <= 100) grade = ‘A’); else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘E’; Note how the sequence is important here and must use else if rather than just if (why?)
21
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 21 if-else if-else if-…-else Non-Example?? if (profRel.equals(“colleague”) ) greeting = “Daniel”; else if (profRel.equals(“friend”) ) greeting = “Dan”; else if (profRel.equals(“grad student”) ) greeting = “DP”; else if (profRel.equals(“undergrad student”) ) greeting = “Professor”; else greeting = “Mr. Port”;
22
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 22 End of Review
23
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 23 Iteration r Summary of loops m while-do m for m do-while r while loop examples r for loop examples
24
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 24 Iteration r Traditional method of repeating statements (not using recursion) loop control { --------------- } repeat these statements zero or more times, controlled by loop control
25
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 25 Iteration (cont.) r Three different forms of iteration while for m do-while
26
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 26 While loops while ( condition ) statement contains variables that are changed in loop repeat until condition becomes false Keep in mind that statement can be a compound or block statement.
27
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 27 For loops for ( init ; cond ; incr ) Statement init ; //for condition while ( cond ) { Statement incr ; } Mostly for convenience and readability
28
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 28 Do-while loops do Statement while ( cond ) Statement ; while ( cond ) Statement
29
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 29 While loops Syntax: while ( cond ) statement r What it means: Test cond. If false, then while loop is finished; go on to next statement If true, execute statement, then go back and start again Continue like this until cond becomes false.
30
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 30 While loop examples while (true) System.out.println(“I will do the reading assignments”); while (false) System.out.println(“I will start my HW early”); Output?
31
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 31 More while loop examples int x = 5; while (x>0) { System.out.println(x); x = x-1; }
32
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 32 More while loop examples int x = 5; int s = 0; while (x > 0) { s = s+x; x = x-1; }
33
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 33 More while loop examples int s = 0; int x = 1; while (x <= 10) { s = s+x; x = x+1; }
34
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 34 for loops r Convenient syntax for loops with loop variables that are incremented or decremented each time through the loop (as in previous examples). r Recall: for ( init ; cond ; incr ) statement init ; while ( cond ) { statement incr ; }
35
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 35 for loop examples Previous examples: int s = 0; int x = 5; while (x > 0) { s = s+x; x = x-1; } int s = 0; for (int x = 5; x > 0; x = x-1) s = s+x;
36
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 36 for loop examples int s = 0; for (int x = 1; x <= 10; x = x+1) s = s+x; int s = 0; int x = 1; while (x <= 10) { s = s+x; x = x+1; }
37
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 37 for loop usage for (i = 1; i <= n ; i = i+1) statement One use of for loops is simply to execute a statement, or sequence of statements, a fixed number of times: executes statement exactly n times.
38
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 38 for loop usage (cont.) for (int i = 1; i <= 100; i = i+1) System.out.println( “I will not turn HW in at 11:59PM.”); Example: print “I will not turn HW in at 11:59PM” a hundred times.
39
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 39 for loop usage (cont.) int xpow = 1; for (i = 1; i <= n; i = i+1) xpow *= xpow; Example: raise x to the n’th power.
40
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 40 for loop usage (cont.) for (int i = 0; i < 20; i = i+1) if (i%2 == 0) System.out.println (“My robot loves me “); else System.out.println (“My robot loves me not“); Keep in mind that loop bodies can be as complicated as you like. This loop prints “My robot loves me” and “My robot loves me not” on alternate lines, ten times each:
41
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 41 for loop usage (cont.) class Love { public static void main(String args[]) { for (int i = 0; i < 20; i = i+1) { System.out.print("My robot loves me”); if (i%2 == 0) System.out.println(“"); else System.out.prinln (“ not"); } An alternate approach. Which is more “elegant”?
42
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 42 The exit Method If you have a program situation where it is pointless to continue execution you can terminate the program with the exit(n) method n is often used to identify if the program ended normally or abnormally n is conventionally 0 for normal termination and non-zero for abnormal termination
43
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 43 exit Method Example System.out.println("Enter e to exit or c to continue"); char userIn = SavitchIn.readLineChar(); if(userIn == 'e') System.exit(0); else if(userIn == 'c') { //statements to do work } else { System.out.println("Invalid entry"); //statements to something appropriate }
44
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 44 Some Practical Considerations When Using Loops r The most common loop errors are unintended infinite loops and off-by-one errors in counting loops m An off-by-one error is an error that occurs when a loop is executed one too many or one too few times. r Sooner or later everyone writes an unintentional infinite loop To get out of an unintended infinite loop enter ^C (control-C) r Loops should tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one and other possible errors
45
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 45 Tracing a Variable in a Loop r Tracing a variable: print out the variable each time through the loop r A common technique to test loop counters and troubleshoot off-by-one and other loop errors r Some systems provide a built-in tracing system that allows you to trace a variable without having to change your program. r If no built-in utility is available, insert temporary output statements to print values.
46
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 46 The Type boolean r A primitive type r Can have expressions, values, constants, and variables just as with any other primitive type Only two values: true and false Can use a boolean variable as the condition in an if statement r Using a boolean variable as the condition can make an if statement easier to read by avoiding a complicated expression. if (systemsAreOK) System.out.println(“Initiate launch sequence.”); else System.out.println(“Abort launching sequence”);
47
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 47 boolean Variables in Assignments A boolean expression evaluates to one of the two values true or false. The value of a boolean expression can be assigned to a boolean variable: int number = -5; boolean isPositive; isPositive = (number > 0); if (isPositive) System.out.println(“positive”); else System.out.println(“negative or zero”); There are simpler and easier ways to write this small program, but boolean variables are useful in keeping track of conditions that depend on a number of factors. Parentheses are not necessary here. Parentheses are necessary here.
48
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 48 Truth Tables for boolean Operators Value of AValue of BA && B truetruetrue truefalsefalse falsetruefalse falsefalsefalse Value of AValue of BA || B truetruetrue truefalsetrue falsetruetrue falsefalsefalse Value of A!A truefalse falsetrue && (and)|| (or) ! (not)
49
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 49 Precedence An example of using precedence rules to see which operators in following expression should be done first: score 90 r Division operator has highest precedence of all operators used here so treat it as if it were parenthesized: score 90 r Subtraction operator has next highest precedence : score 90 r The operators have equal precedence and are done in left-to-right order : (score 90) r The last expression is a fully parenthesized expression that is equivalent to the original. It shows the order in which the operators in the original will be evaluated.
50
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 50 Precedence Rules Highest Precedence First: the unary operators: +, -, ++, --, and ! Second: the binary arithmetic operators: *, /, % Third: the binary arithmetic operators: +, - Fourth: the boolean operators:, = = Fifth: the boolean operators: ==, != Sixth: the boolean operator & Seventh: the boolean operator | Eighth: the boolean operator && Ninth: the boolean operator || Lowest Precedence
51
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 51 Short-Circuit Evaluation r Short-circuit evaluation—only evaluating as much of a boolean expression as necessary. r Example: If assign > 0 is false, then the complete expression cannot be true because AND is only true if both operands are true. r Java will not evaluate the second part of the expression. Short-circuit evaluation prevents a divide-by-zero exception when assign is 0. if ((assign > 0) && ((total/assign) > 60)) System.out.println(“Good work”); else System.out.println(“Work harder.”);
52
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 52 Summary Part 1 Java selection statements: if, if-else, if- else if, and switch Java repetition (loop) statements: while, do- while, and for r Loops can be counter or sentinel controlled r Any loop can be written any of the three loop statements, but while and do-while are good choices for sentinel loops for is a good choice for counting loops
53
1/28/03ITM352 Fall 2003 Class 5 – Control Flow 53 Summary Part 2 Unintended infinite loops can be terminated by entering ^C (control-C) r The most common loop errors are unintended infinite loops and off-by-one errors in counting loops Branching and loops are controlled by boolean expressions boolean expressions are either true or false boolean is a primitive data type in Java exit(n) is a method that terminates a program n = 0 is the conventional value for normal termination
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.