1 / 53

Chapter 3- Flow Control

Chapter 3- Flow Control. Overview. Why flow control Branches vs. Loops Branch statements Loop Statements Complex loops Boolean variables Review. Why Flow Control. Why Flow Control?. Can perform more complex programs. Can write programs with less code.

eron
Download Presentation

Chapter 3- Flow Control

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. Chapter 3- Flow Control

  2. Overview • Why flow control • Branches vs. Loops • Branch statements • Loop Statements • Complex loops • Boolean variables • Review

  3. Why Flow Control

  4. Why Flow Control? • Can perform more complex programs. • Can write programs with less code. • Sometimes makes it easier to understand what is going on in the code.

  5. Branches vs. Loops • Branches are used for statements that you want to run conditionally (only on certain input). • Loops are used to repeat statements without having to write the programs over and over and over...

  6. Branches

  7. Branches • Two main types of branches: • if-else (sometimes does not include the else). • switch (the same thing as multiple if statements).

  8. if-else statement Don’t put a semicolon at the end of these statements. if(<condition>) { <statements>; } else { <statements>; } You don’t need to include the else section if you don’t want. Can be one or more statements here. If only doing one statement, don’t need curly braces({ or }), but it doesn’t hurt to have them there either.

  9. Conditions • Some sort of inequality: == (equal), !=(not equal), >=(greater than or equal), <=(less than or equal), >(greater than), <(less than). • The above only work on primitives, for using class objects, you use .equals() string1.equals(“Hello there”); string1.equals(string2);

  10. Ands and Ors • You can also combine multiple conditions with either the AND operator “&&” or the OR operator “||” (that’s two “pipes” which are usually located above the backslash character “\”). • Examples if((char1==‘y’) || (char1==‘n’)) //if y or n If(int1 >0 && int1 < 100) //if between 0 and 100

  11. Boolean Logic • AND logic • True && True = True • True && False = False • False && True = False • False && False = False • OR logic • True || True = True • True || False = True • False || True = True • False || False = False

  12. An if-else example ... System.out.println(“Please enter y or n.”); char letter = SavitchIn.readLineNonwhiteChar(); if(letter == ‘y’) //if they pressed y { System.out.println(“You entered ‘y’”); } else //if they didn’t press y { //NOTE- this doesn’t mean they pressed n //They could have pressed g or something System.out.println(“You didn’t enter ‘y’”); } ...

  13. More on if-else statements • Be careful that what you do in your else statement is truly for the negation of the if condition(as in the last example). • Can nest them(put an if-else statement as one of the statements inside another if-else statement), just be careful when doing this.

  14. More complicated example char char1= SavitchIn.readLineNonwhiteChar(); if(char1 == ‘a’) { System.out.println(“You pressed a.”); } else if(char1 == ‘b’) { System.out.println(“You pressed b.”); } else System.out.println(“You pressed garbage.”); Nested if-else statements. Note, each if-else statement counts as a single statement, so we don’t really need curly braces around the second if-else statement(it is the “single” statement for the else part.

  15. switch statements • Use when you would have multiple if statements checking the condition of the same variable. • For large cases it is easier to read and easier to alter.

  16. The format of switch Some integer or character expression (can’t use String or any other type). switch(<variable>) { case <value1>: <statements>; break; case <value2>: <statements>; break; ... case <valueI>: <statements>; break; default: <statements>; break; } One or more statements(don’t need curly braces in switches, but it won’t hurt either) Always, always, always end a case with a break. Else the program will continue running into other cases. What the computer does if the variable doesn’t match any of the above values.

  17. Alternate way of doing ‘a’, ‘b’ example char char1=SavitchIn.readLineNonwhiteChar(); switch(char1) { case ‘a’: System.out.println(“You pressed a.”); break; case ‘b’: System.out.println(“You pressed b.”); break; default: System.out.println(“You pressed garbage”); break; }

  18. Loops

  19. Loops • Loops help us repeat steps over and over without us having to write the code over and over. • There are three main kinds of loops: • while statements • do-while statements • for statements

  20. while statements • Repeats the body of the statement until the condition is false. Will loop zero or more times. • Looks like: Some sort of boolean expression(like equality). Just like with if-else. while(<condition>) { <statements>; } Note, again there is no semicolon at the end of the line. Don’t put one there. Again, like the branch statements, this can be one or more lines. If it is only one statement, you can remove the curly braces.

  21. Two while examples(what does the following print to the screen?): ... int max = 10, count = 1; while(count <= max) { System.out.println(count); count++; } while(count<=max) { System.out.println(max); count++; } ...

  22. What they print to the screen: 1 2 3 … 9 10 Nothing, count is already bigger than max(that is how it got out of the last loop). ... int max = 10, count = 1; while(count <= max) { System.out.println(count); count++; } while(count<=max) { System.out.println(max); count++; } ...

  23. do-while statement • The do while statement is similar to the while statement, except it is executed at least once(while statement can sometimes execute 0 times). • Looks like: The do-while statement is the only, I repeat only, looping or branch statement that requires a semi-colon at the end of the statement. do { <statements>; } while(<condition);

  24. Do-while example(what is output?) ... int max = 10, count = 1; do { System.out.println(count); count++; } while(count <= max); do { System.out.println(max); count++; } while(count<=max) ...

  25. What they print to the screen: 1 2 3 … 9 10 10, as do-whiles always execute at least once ... int max = 10, count = 1; do { System.out.println(count); count++; } while(count <= max); do { System.out.println(max); count++; } while(count<=max) ...

  26. The mighty for statement! • The for loop is another repeating loop that makes it really easy to specify a range in which the loop repeats. • Looks like: for(<initializers>;<condition>;<updaters>) { <statements>; } Again, no semicolon at the end!

  27. The for statement dissected for(<initializers>;<condition>;<updaters>) { <statements>; } • Initializers- Optional. Any statements placed in this area will be executed once before entering the loop(or any testing of conditions). • Condition- Required. Some boolean expression just like in while statements. While it is true, the statements in the loop are executed. When it is false, the computer skips over the for loop and continues on with the program. • Updaters- Optional. Any statements in this area will be run whenever the for-statement finished all of the instructions in the statements section.

  28. A for example ... for(int count = 1; count <= 4; count++) System.out.println(“Howdy: “ + count); ... Output: Howdy: 1 Howdy: 2 Howdy: 3 Howdy: 4

  29. Another for example A for statement without initializers or updaters is basically a while loop ... int counter = 1; for(; count <= 4; ) { System.out.println(“Howdy: “ + count); count++; } ... Output: Howdy: 1 Howdy: 2 Howdy: 3 Howdy: 4

  30. More than one initializer or updater. • You can have more than one initializer or updater. • Just use a comma “,” between each statement in the section (why not a semicolon like usual?). • Do NOT use a comma for the condition, use && or || to combine multiple parts. • Like so: for(int i=0, int j=0; i<=3; j++, i+=j) System.out.println(i);

  31. What will this output (look carefully): ... for(int i=0, int j = 1; i<=4; j++) System.out.println(j); ...

  32. What is output: ... for(int i=0, int j = 1; i<=4; j++) System.out.println(j); ... 1 2 3 4 5 6 . . . INFINITE LOOP!!!!

  33. Infinite loop-constant danger • Infinite loops are common when programming while, do-while, and for statements. • Always, always, always make sure that your condition will eventually fail(make sure you increment variables). Else your program will continue forever. • To kill infinite loops, close the window or press ctrl-c or sometimes ctrl-z.

  34. Which of these have infinite loops? ………………………………………………………………… int j = 1; while(j>=1); { System.out.println(j); j++; } ………………………………………………………………… int k = 1; do { System.out.println(k); k+=2; } while(k != 6); ………………………………………………………………… for(int i=1;i>=1;i++) System.out.println(i);

  35. Answer: All of them! Semicolon stops anything from happening in while loop, including the increment of j. ………………………………………………………………… int j = 1; while(j<=10); { System.out.println(j); j++; } ………………………………………………………………… int k = 1; do { System.out.println(k); k+=2; } while(k != 6); ………………………………………………………………… for(int i=1;i>=1;i++) System.out.println(i); Starts off as 1, an odd number. Always adding 2 so k will stay odd. So k will never be even and won’t be 6. It will skip right over it. Starts off as 1 and increases, so will never be less than 1, so the condition will never be false.

  36. Sentinels and loops for user input • A “sentinel” is a special character or number specified by you to end a loop of user input. • When using sentinels, you will test the user input against the sentinel in the condition area of you loop.

  37. A sentinel example • Write a loop that will ask a user for a list of non-negative integers. You will produce the sum of all the integers. The user signifies the end of their list by entering a sentinel value that is a negative number(any negative number will do).

  38. Sentinel example- For loop. ... int sum = 0, userInput; System.out.println(“Enter a number(neg. to quit):”); userInput = SavitchIn.readLineInt(); while(userInput >= 0) { sum += userInput //sum = sum + userInput System.out.println(“Enter another number: “); userInput = SavitchIn.readLineInt(); } System.out.println(“The sum is: “ + sum); ...

  39. Other rules about loops • You should never declare a variable inside the body of a looping statement. • Watch out for infinite loops! • Off-by-one errors are common. Test often. • When making any changes to a loop, always retest the whole thing. You may have broken something else in your fix.

  40. Complex Loops

  41. Complex loops. • Single loops are relatively easy to grasp, but there are things that can happen that make them much more difficult • An exit or break statement can end a loop prematurely. • Nested loops can also be very useful, but can also be very confusing.

  42. break and exit • break will jump you directly out of any loop(or switch). It will jump you out only one level(if you have things nested). It won’t work with if-else statements though. • System.exit(0) will exit completely out of the Java program.

  43. break and exit examples ... int i = 0; while(i<=10) { System.out.println(i); i++; break; } System.out.println(i); ... int k = 0; while(k<=10) { System.out.println(k); I++; System.exit(0); } System.out.println(k); ...

  44. Output of examples ... int i = 0; while(i<=10) { System.out.println(i); i++; break; } System.out.println(i); ... int k = 0; while(k<=10) { System.out.println(k); k++; System.exit(0); } System.out.println(k); ... 1 2 1

  45. Nesting loops • Good for doing two dimensional (or more dimensions) things, tables of information, basic ASCII art, etc. • 2-D: Usually use the outer loop to control the rows and the inner loops to control the columns.

  46. A nested loop example int i,j; for(i=1; i<=4;i++) { for(j=1; j<=i; j++) System.out.print(“*”); System.out.println(“ “); }

  47. A nested loop example output Make 4 rows int i,j; for(i=1; i<=4;i++) { for(j=1; j<=i; j++) System.out.print(“*”); System.out.println(“ “); } For each column up to the ith column do the following Write a single asterisk(no new line) * ** *** **** After writing out all the columns for a row, put in a new line.

  48. Boolean Variables

  49. Boolean Variables • A boolean is a primitive type that can only have the values true and false • Can be used wherever a Boolean expression is required (like a condition in an if-else or for statement). • Can make code easier to read sometimes.

  50. boolean <variable>; <variable>=<booleanExp>; if(<boolean_variable>) boolean AOK, isLastNum; isLastNum = true; AOK = (temperature>32) && (sunlight > 6); If(AOK) { System.out.println( “All systems go.”); } boolean variable form

More Related