1 / 53

ITM352 Loops Lecture #6

ITM352 Loops Lecture #6. Announcements. Lab class dates have changed!!! Check the “Weekly Schedule” for details Go to E 102, NOT this classroom!!! Listserv (ITM352-L) All class announcements will go out on this list (not via my mail alias anymore)

espen
Download Presentation

ITM352 Loops Lecture #6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ITM352LoopsLecture #6

  2. Announcements • Lab class dates have changed!!! • Check the “Weekly Schedule” for details • Go to E 102, NOT this classroom!!! • Listserv (ITM352-L) • All class announcements will go out on this list (not via my mail alias anymore) • Hints, answers to questions (non-personal), etc. • Quizzes were terrible… • I’m going to drop this one for everyone • We’ll try again soon… • Need to re-think class structure

  3. ** Important Notice ** • Section 2 • 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 • If you absolutely cannot make these lectures, come see me RIGHT AWAY

  4. Today • Quiz answers • What’s the problem here? • New class schedule • Review • Documentation and Coding Style • Control Flow • Conditionals (decisions) • New topic • Loops • Review of previous material • You ask, I answer

  5. Quiz #1 Answers Name: __Prof. Port_________ ID #: ____123-45-678_______ • Write a Java statement that declares a variable of typefloat 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 compoundconditional expression with a type booleanreturn 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. What’s The Problem? • Is the material too obscure? • Presentation to fast? • Class too unorganized? • Not interesting? • What suggestions do you have that might help? • Be responsible! • When you are confused or need help ** seek help ** • Do not put things off! • Read through the assigned sections of the book BEFORE lecture • If you have a problem, come see me BEFORE it becomes an un-fixable problem.

  7. New Class Schedule

  8. Review

  9. Documentation and Style • Use meaningful names for variables, classes, etc. • Use indentation and line spacing as shown in the examples in the text • 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. Indentation • Codes inside a block should be indented. • Indent 2 to 4 spaces • Be consistent.

  11. Named Constants • Named constant—using a name instead of a value • Example: use TAX_RATE instead of 5.25 • Advantages of using named constants • Easier to understand program because reader can tell how the value is being used • Easier to modify program because value can be changed in one place (the definition) instead of being changed everywhere in the program. • Avoids mistake of changing same value used for a different purpose

  12. Defining Named Constants public static final double PI = 3.14159; 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 • The remainder of the definition is similar to a variable declaration and gives the type, name, and initial value. • A declaration like this is usually at the beginning of the file and is not inside the main method definition.

  13. What is “Flow of Control”? • Flow of Control is the execution order of instructions in a program • 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 • either go to the next instruction • or jump to some other instruction 3. Repetition - a loop (repeat a block of code) at the end of the loop • either go back and repeat the block of code • or continue with the next instruction after the block • Selection and Repetition are called Branching since these are branch points in the flow of control

  14. Sequence the default Java automatically executes the next instruction unless you use a branching statement Branching: Selection if if-else if-else if-else if- … - else switch Branching: Repetition while do-while for Java Flow Control Statements

  15. Boolean Expressions • Boolean expressions can be thought of as test conditions (questions) that are either true or false • Often two values are compared • For example:Is A greater than B?Is A equal to B?Is A less than or equal to B?etc. • A and B can be any data type (or class), but they should be the same data type (or class)

  16. Java Comparison Operators

  17. theRobot == aRobot is true myRobot == theRobot is false aRobot myRobot theRobot Comparing objects • Great care must be taken when comparing objects: • Statements like myRobot == theRobot compare references to where the objects are stored, not the objects themselves! • In general the equals() method is used • The objects themselves define what it means for objects to be equal

  18. Example: Comparison Methods forString Class • “==“ does not do what you may think for String objects • 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 • are they stored in the same location? • more will be said about this later • 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. Compound Boolean Expressions • Use && to AND two or more conditions • Use || to OR two or more conditions • See text for definitions of AND and OR • 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) • In this example the parentheses are not required but are added for clarity • See text (and later slides) for Precedence rules • 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. 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. 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. End of Review

  23. Iteration • Summary of loops • while-do • for • do-while • while loop examples • for loop examples

  24. Iteration • Traditional method of repeating statements (not using recursion) loop control{ --------------- --------------- } repeat these statements zero or more times, controlled by loop control

  25. Iteration (cont.) • Three different forms of iteration • while • for • do-while

  26. While loops contains variables that are changed in loop while (condition) statement repeat until condition becomes false Keep in mind that statement can be a compound or block statement.

  27. For loops init; //for condition while (cond) { Statement incr; }  for (init; cond; incr) Statement Mostly for convenience and readability

  28. Do-while loops Statement; while (cond) Statement do Statement while (cond) 

  29. While loops • Syntax: while (cond) statement • What it means: Test cond.If false, then while loop is finished; go on to next statementIf true, execute statement, then go back and start again Continue like this until cond becomes false.

  30. While loop examples while (true) System.out.println(“I will do the reading assignments”); Output? while (false) System.out.println(“I will start my HW early”); Output?

  31. More while loop examples int x = 5; while (x>0) { System.out.println(x); x = x-1; }

  32. More while loop examples int x = 5; int s = 0; while (x > 0) { s = s+x; x = x-1; }

  33. More while loop examples int s = 0; int x = 1; while (x <= 10) { s = s+x; x = x+1; }

  34. for loops • Convenient syntax for loops with loop variables that are incremented or decremented each time through the loop (as in previous examples). • Recall: init; while (cond) { statement incr; }  for (init; cond; incr) statement

  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. for loop examples int s = 0; int x = 1; while (x <= 10) { s = s+x; x = x+1; } int s = 0; for (int x = 1; x <= 10; x = x+1) s = s+x; 

  37. for loop usage One use of for loops is simply to execute a statement, or sequence of statements, a fixed number of times: for (i = 1; i <= n; i = i+1) statement executes statement exactly n times.

  38. for loop usage (cont.) Example: print “I will not turn HW in at 11:59PM” a hundred times. for (int i = 1; i <= 100; i = i+1) System.out.println( “I will not turn HW in at 11:59PM.”);

  39. for loop usage (cont.) Example: raise x to the n’th power. int xpow = 1; for (i = 1; i <= n; i = i+1) xpow *= xpow;

  40. for loop usage (cont.) 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: 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“);

  41. for loop usage (cont.) An alternate approach. Which is more “elegant”? 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"); } } }

  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. 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. Some Practical ConsiderationsWhen Using Loops • The most common loop errors are unintended infinite loops and off-by-one errors in counting loops • An off-by-one error is an error that occurs when a loop is executed one too many or one too few times. • Sooner or later everyone writes an unintentional infinite loop • To get out of an unintended infinite loop enter ^C (control-C) • Loops should tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one and other possible errors

  45. Tracing a Variable in a Loop • Tracing a variable: print out the variable each time through the loop • A common technique to test loop counters and troubleshoot off-by-one and other loop errors • Some systems provide a built-in tracing system that allows you to trace a variable without having to change your program. • If no built-in utility is available, insert temporary output statements to print values.

  46. The Type boolean • A primitive type • 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 • 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. 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. Value of A Value of B A && B true true true true false false false true false false false false Value of A Value of B A || B true true true true false true false true true false false false Value of A !A true false false true Truth Tables for boolean Operators && (and) || (or) ! (not)

  49. Precedence An example of using precedence rules to see which operators in following expression should be done first: score < min/2 – 10 || score > 90 • Division operator has highest precedence of all operators used here so treat it as if it were parenthesized: score < (min/2) – 10 || score > 90 • Subtraction operator has next highest precedence : score < ((min/2) – 10) || score > 90 • The < and > operators have equal precedence and are done in left-to-right order : (score < ((min/2) – 10)) || (score > 90) • 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. 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

More Related