Chapter 3- Flow Control. Overview n Why flow control n Branches vs. Loops n Branch statements n Loop Statements n Complex loops n Boolean variables n.

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Computer Science 1620 Loops.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops – While, Do, For Repetition Statements Introduction to Arrays
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
CPS120: Introduction to Computer Science Decision Making in Programs.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CSC 142 I 1 CSC 142 Iterations [Reading: chapter 6]
Lecture 4 Control Structures MIT – AITI What are Control Structures? Control structures are a way to alter the natural sequence of execution in.
Flow of Control Chapter 3 Flow of control Branching Loops
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Chapter 4: Control Structures II
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Control Flow Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
CS 106 Introduction to Computer Science I 09 / 26 / 2007 Instructor: Michael Eckmann.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Application development with Java Lecture 6 Rina Zviel-Girshin.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
Loops.
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 5: Control Structures II
Loop Structures.
CiS 260: App Dev I Chapter 4: Control Structures II.
Outline Altering flow of control Boolean expressions
Chapter 3 Flow of Control Loops in Java.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Chapter 3- Flow Control

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

Why Flow Control

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

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

Branches

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

if-else statement if( ) { ; } else { ; } Don’t put a semicolon at the end of these statements. 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. You don’t need to include the else section if you don’t want.

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

Ands and Ors n 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 “\”). n Examples if((char1==‘y’) || (char1==‘n’)) //if y or n If(int1 >0 && int1 < 100) //if between 0 and 100

Boolean Logic n AND logic –True && True = True –True && False = False –False && True = False –False && False = False n OR logic –True || True = True –True || False = True –False || True = True –False || False = False

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’”); }...

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

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.

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

The format of switch switch( ) { case : ; break; case : ; break;... case : ; break; default: ; break; } Some integer or character expression (can’t use String or any other type). 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.

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; }

Loops

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

while statements n Repeats the body of the statement until the condition is false. Will loop zero or more times. n Looks like: while( ) { ; } Some sort of boolean expression(like equality). Just like with if-else. 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.

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++; }...

What they 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++; } … 9 10 Nothing, count is already bigger than max(that is how it got out of the last loop).

do-while statement n The do while statement is similar to the while statement, except it is executed at least once(while statement can sometimes execute 0 times). n Looks like: do { ; } while(<condition); 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-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)...

What they print to the screen: … , 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)...

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

The for statement dissected for( ; ; ) { ; } n Initializers- Optional. Any statements placed in this area will be executed once before entering the loop(or any testing of conditions). n 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. n Updaters- Optional. Any statements in this area will be run whenever the for-statement finished all of the instructions in the statements section.

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

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

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

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

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

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

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);

Answer: All of them! ………………………………………………………………… 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); Semicolon stops anything from happening in while loop, including the increment of j. 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.

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

A sentinel example n 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).

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);...

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

Complex Loops

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

break and exit n 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. n System.exit(0) will exit completely out of the Java program.

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);...

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);

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

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(“ “); }

A nested loop example output int i,j; for(i=1; i<=4;i++) { for(j=1; j<=i; j++) System.out.print(“*”); System.out.println(“ “); } * ** *** **** Make 4 rows 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.

Boolean Variables

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

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

Guides for expressions When working with complicated Boolean expressions (lots of &&s and ||s) or complicated arithmetic expressions (lots of math symbols) put parentheses around the parts of the expression you want evaluated first. Or see the precedence table (p. 194). (4+5)*(6+7) = *6+7 = 41 (true || false) && false = false true || false && false = true

Review

n Branches for conditional execution –What are the names of the statements? –What symbol should never come at the end of an if-else statement? n Loops are for repeated execution –What are the names of the statements? –What things should you be careful of in loops? n Boolean variables can be used in the place of Boolean expressions