How would you handle the case for when a user selects an option? 1/15/2016 CSE 11 WINTER LEC 6 2

Similar documents
Building Java Programs

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Building Java Programs

Building Java Programs

STUDENT LESSON A12 Iterations

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Building Java Programs

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

ECE 122. Engineering Problem Solving with Java

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

CompSci 125 Lecture 11

Outline for Today CSE 142. Programming a Teller Machine. CSE142 Wi03 I-1. ATM Algorithm for Dispensing Money

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Scope of this lecture. Repetition For loops While loops

Loops. CSE 114, Computer Science 1 Stony Brook University

CS111: PROGRAMMING LANGUAGE II

Repetition, Looping. While Loop

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

CS1100 Introduction to Programming

Type boolean. Building Java Programs. Recap: Type boolean. "Short-circuit" evaluation. De Morgan's Law. Boolean practice questions.

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Accelerating Information Technology Innovation

More on control structures

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

CSE 114 Computer Science I

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Introduction. C provides two styles of flow control:

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Advanced if/else & Cumulative Sum

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Flow Control. CSC215 Lecture

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

Computer Programming

CS 112 Introduction to Programming. Exercise: MatchDB. match1. Removing break. Solution I: Using break. Loop Patterns: break; Fencepost.

Building Java Programs

Assignment 2.4: Loops

Combo Lecture Lecture 14/15. Instructor: Craig Duckett

Problem Solving With Loops

AP COMPUTER SCIENCE A

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Exam 2, Version 2. For the following code, mark True or False for statements 1.8 to 1.10.

Topic 14 while loops and loop patterns

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

EECS 211 Lab 2. Getting Started. Getting the code. Windows. Mac/Linux

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Chapter 2: Basic Elements of Java

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Flow Control: Branches and loops

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Top-Down Program Development

Chapter Goals. Contents LOOPS

Advanced Computer Programming

Introduction to the Java Basics: Control Flow Statements

Iteration statements - Loops

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

printf( Please enter another number: ); scanf( %d, &num2);

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

PROGRAMMING FUNDAMENTALS

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

CSC 1051 Data Structures and Algorithms I

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

CMPT 125: Lecture 4 Conditionals and Loops

Example: Monte Carlo Simulation 1

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

Chapter 13 Control Structures

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

CSC 1051 Data Structures and Algorithms I

Score score < score < score < 65 Score < 50

Repetition CSC 121 Fall 2014 Howard Rosenthal

LOOPS. Repetition using the while statement

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

SSOL Language Reference Manual

C++ Programming: From Problem Analysis to Program Design, Third Edition

CS110D: PROGRAMMING LANGUAGE I

CSC 1051 Data Structures and Algorithms I

Last Class. While loops Infinite loops Loop counters Iterations

LECTURE 5 Control Structures Part 2

Chapter 4 Introduction to Control Statements

Initial Coding Guidelines

5. Control Statements

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Full file at

Introduction to Java Applications

Data Structure and Programming Languages

Transcription:

Lecture 6: Loops G U E S T L E C T U R E R J U S T I N H S I A U N I V E R S I T Y O F C A L I F O R N I A, S A N D I E G O C S E 1 1 - I N T R O D U C T I O N TO C O M P U T E R S C I E N C E A N D O B J E C T - O R I E N T E D P R O G R A M M I N G : JAVA

How would you handle the case for when a user selects an option? 1/15/2016 CSE 11 WINTER 2016 - LEC 6 2

1/15/2016 CSE 11 WINTER 2016 - LEC 6 3

Switch Statements switch(variable) { case 3: //code break; case 8: //code break; default: //code break; 1/15/2016 CSE 11 WINTER 2016 - LEC 6 4

Switch Statements switch(variable) { case 3: //code break; case 8: //code break; default: //code break; if (variable == 3) { //code else if (variable == 8) { //code else { //code 1/15/2016 CSE 11 WINTER 2016 - LEC 6 5

What s the final value of z if program starts with z=0? z=2? switch(z) { case 1: z*=2; case 2: z*=3; case 5: z+=1; case 6: z--; default: z=0; A) 6,0 B) 0,0 C) 0,6 D)C.E. E) Runtime error 1/15/2016 CSE 11 WINTER 2016 - LEC 6 6

If Asked to draw this image. How would you do it with what you know so far. 1/15/2016 CSE 11 WINTER 2016 - LEC 6 7

If Asked to draw this image. How would you do it with what you know so far. draw(lemon); draw(lemon); newline(); draw(bluething); draw(bluething); 1/15/2016 CSE 11 WINTER 2016 - LEC 6 8

Check if you can eliminate any candy. if(square1_1 == square1_2 square1_1 == square2_1 square2_1 == square2_2 square1_2 == sqaure2_2) { removecandy(); addnewcandy(); printinspiringmessage(); 1/15/2016 CSE 11 WINTER 2016 - LEC 6 9

1/15/2016 CSE 11 WINTER 2016 - LEC 6 10

Motivating Example Code instruction-by-instruction? Drawing example? Regular polygon example? Batch example? Sum/accumulator example? 1/15/2016 CSE 11 WINTER 2016 - LEC 6 11

Why Loop? Want to do the same thing over and over again Save time typing out all instructions Generalize procedure if changing by same amount 1/15/2016 CSE 11 WINTER 2016 - LEC 6 12

Lecture Outline Loops while loops do-while loops break and continue 1/15/2016 CSE 11 WINTER 2016 - LEC 6 13

Loops There are three looping statements in Java: Indefinite # of repeats not known in advance 1. while 2. do-while Definite executes a known # of times 3. for 1/15/2016 CSE 11 WINTER 2016 - LEC 6 14

while Loops Syntax: while(condition) { // code // update condition variable Flow chart: Start Condition? False End True Loop Body 1/15/2016 CSE 11 WINTER 2016 - LEC 6 15

while Example 1 int num = 9; int indexlemons = 0; while ( indexlemons < num ) { System.out.print( indexlemons + ); indexlemons++; 1/15/2016 CSE 11 WINTER 2016 - LEC 6 16

while Example 1 int num = 9; int indexlemons = 0; while ( indexlemons < num ) { System.out.print( indexlemons + ); indexlemons++; Output: 0 1 2 3 4 5 6 7 8 How many times did the loop execute? 9 1/15/2016 CSE 11 WINTER 2016 - LEC 6 17

while Example 2 Want to find smallest factor > 1 of a number Factor: natural number divisor 1 is a factor of all natural numbers not interesting Example: 30 Factors: 1, 2, 3, 5, 6, 10, 15, 30 How can we tell if i is a factor of n? Modulo! Factor if i%n==0 1/15/2016 CSE 11 WINTER 2016 - LEC 6 18

while Example 2 // Find a number s smallest factor > 1 Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int number = console.nextint(); int factor = 2; while ( number%factor!= 0) { factor++; System.out.println("First factor: " + factor); How many times does the loop execute if: number = 5 number = 4 number = 1 3 times 0 times times! 1/15/2016 CSE 11 WINTER 2016 - LEC 6 19

do-while Loops Syntax: do { // code // update condition variable while(condition); Flow chart: Start Condition? False End True Loop Body 1/15/2016 CSE 11 WINTER 2016 - LEC 6 20

What does this code do? Scanner scnr = new Scanner(System.in); int entered = 0; do { entered++; System.out.print( Enter \ quit\ to exit: ); while (!scnr.next().equals( quit )); (A) Runs loop once and then exits (B) Counts the # of user responses until seeing quit (excluding quit) (C) Counts the # of user responses until seeing quit (including quit) (D) The loop never executes (E) None of the above 1/15/2016 CSE 11 WINTER 2016 - LEC 6 21

True or False? I can write any do-while loop as a while loop. True, copy loop body above I can write any while loop as a do-while loop. False, case where loop body never executed I can write a definite loop using while. True, use counter variable 1/15/2016 CSE 11 WINTER 2016 - LEC 6 22

Stretch Break while ( myself.stillawake() ) { sheep++; 1/15/2016 CSE 11 WINTER 2016 - LEC 6 23

Common Looping Errors Family Feud-style, can you name some of the most common errors with do-while looping? Forgetting to update (infinite loop) Off-by-one error Forgotten semi-colon Bad/lack of initialization 1/15/2016 CSE 11 WINTER 2016 - LEC 6 24

Infinite Loops These are almost always bad Loop body is continuously executing Notable exception: embedded systems Symptom: program never responds Force quit or kill process Common causes Bad/missing update code Unexpected input/initialization 1/15/2016 CSE 11 WINTER 2016 - LEC 6 25

Manipulating Body Execution What if we don t want the loop body to execute every time? break exit loop early continue skip rest of this iteration 1/15/2016 CSE 11 WINTER 2016 - LEC 6 26

break Example while (nmoves > 0) { user_input; if(numcherries == 2 && numpeaches == 1) { break; 1/15/2016 CSE 11 WINTER 2016 - LEC 6 27

break Example 1 We ve seen break before! switch(variable) { case 1: //code break; case 2: //code break; default: //code break; 1/15/2016 CSE 11 WINTER 2016 - LEC 6 28

break Example 2 Now in a loop: int j=0; while(j < 5) { if (j==3) { break; System.out.print(j + ); j++; Prints out: 0 1 2 1/15/2016 CSE 11 WINTER 2016 - LEC 6 29

continue Example What s the output if we use continue instead? int j=0; while(j < 5) { if (j==3) { continue; System.out.print(j + ); j++; (A) 0 1 2 (B) 0 1 2 3 (C) 0 1 2 3 3 3 (D) 0 1 2 4 (E) 0 1 2 4 5 1/15/2016 CSE 11 WINTER 2016 - LEC 6 30

Comparison break ends execution early Good for stop or kill commands Similar to exit condition, doesn t make sense to have at top or bottom of loop code continue moves to next comparison Good for skip commands Make sure doesn t skip over condition variable update 1/15/2016 CSE 11 WINTER 2016 - LEC 6 31

Example: Skip every third num Can we accomplish without using break or continue? 1/15/2016 CSE 11 WINTER 2016 - LEC 6 32