Loops. CSE 114, Computer Science 1 Stony Brook University

Similar documents
CSE 114 Computer Science I

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

CS1150 Principles of Computer Science Loops (Part II)

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Java Coding 3. Over & over again!

Repetition, Looping. While Loop

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

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

Iteration statements - Loops

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Introduction to the Java Basics: Control Flow Statements

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

ECE 122. Engineering Problem Solving with Java

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

Problem Solving With Loops

Lecture 1 Java SE Programming

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

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

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

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

Accelerating Information Technology Innovation

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

ITERATION WEEK 4: EXMAPLES IN CLASS

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Example: Monte Carlo Simulation 1

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

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

Flow of Control: Loops. Chapter 4

STUDENT LESSON A12 Iterations

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

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

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

Loops. GEEN163 Introduction to Computer Programming

CMPT 125: Lecture 4 Conditionals and Loops

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

CSC 1051 Data Structures and Algorithms I

Repetition. Chapter 6

Top-Down Program Development

Last Class. While loops Infinite loops Loop counters Iterations

Repetition. Chapter 6

Selections. CSE 114, Computer Science 1 Stony Brook University

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CS171:Introduction to Computer Science II

CSC 1051 Data Structures and Algorithms I

3chapter C ONTROL S TATEMENTS. Objectives

! 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

Control Structures: if and while A C S L E C T U R E 4

Chapter 3. Selections

Controls Structure for Repetition

CS110D: PROGRAMMING LANGUAGE I

CONDITIONAL EXECUTION

The for Loop. Lesson 11

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

1 Short Answer (10 Points Each)

Midterm Examination (MTA)

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

REPETITION CONTROL STRUCTURE LOGO

Chapter 17. Iteration The while Statement

Course Outline. Introduction to java

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Repetition CSC 121 Fall 2014 Howard Rosenthal

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Bjarne Stroustrup. creator of C++

Full file at

Control Structures II. Repetition (Loops)

Tutorial 3: Conditionals and Iteration COMP 202: Intro to Computing 1

Recap: Assignment as an Operator CS 112 Introduction to Programming

Lecture 14. 'for' loops and Arrays

Over and Over Again GEEN163

CS 101 Spring 2007 Midterm 2 Name: ID:

CompSci 125 Lecture 11

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

Oct Decision Structures cont d

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

Date: Dr. Essam Halim

Computer Programming I - Unit 5 Lecture page 1 of 14

Loops and Expression Types

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

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

Repetition Structures

Chapter Goals. Contents LOOPS

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Transcription:

Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1

Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N? System.out.println("Welcome to Java!");... System.out.println("Welcome to Java!"); Solution: a loop int count = 0; while (count < N) { System.out.println("Welcome to Java"); count++; 2

What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps? Imagine 3 instructions A, B, & C: Instruction A Instruction B Instruction C can be jump to A (meaning go back to A) Iteration might result in: Execute A Execute B Execute C Execute A 3 Execute B...

Why use Iteration? 4 To make our code more practical and efficient To make our code more flexible and dynamic Example: How would we write code to compute N! (factorial), where N is a number entered by the user? Without iteration (or recursion) this would be impractical We do not know N, when we are about to write the program, so we have to check for each N

Without iteration or recursion System.out.print("Enter N: "); int N = Keyboard.nextInt(); int factorial = 1; if((n == 1) (N == 0)) factorial = 1; else if(n == 2) factorial = 2 * 1; else if(n == 3) factorial = 3 * 2 * 1; else if(n == 4) factorial = 4 * 3 * 2 * 1; else if(n == 5) factorial = 5 * 4 * 3 * 2 * 1; System.out.println(factorial); Inefficient coding (repetition)! 5

With iteration System.out.print("Enter N: "); int N = Keyboard.readInt(); int factorial = 1; int i = 1; while(i<=n) factorial *= i++; System.out.println(factorial); 6

Java and iteration 7 We have 3 basic types of iterative statements: while loops do while loops for loops All 3 can be used to do similar things Which one should you use? a matter of individual preference/convenience There is also another kind of for-loop: for each we will see it later when we talk about arrays

while Loop Flow Chart while (loop-continuation-condition) { // loop-body; Statement(s); int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; count = 0; Loop Continuation Condition? false (count < 100)? false true Statement(s) (loop body) true System.out.println("Welcome to Java!"); count++; 8 (A) (B)

Trace while Loop int count = 0; while (count < 2) { Initialize count System.out.println("Welcome to Java!"); count++; 9

Trace while Loop int count = 0; while (count < 2) { (count < 2) is true System.out.println("Welcome to Java!"); count++; 10

Trace while Loop int count = 0; while (count < 2) { Print Welcome to Java System.out.println("Welcome to Java!"); count++; 11

int count = 0; while (count < 2) { Trace while Loop System.out.println("Welcome to Java!"); count++; Increase count by 1 count is 1 now 12

int count = 0; while (count < 2) { Trace while Loop System.out.println("Welcome to Java!"); count++; (count < 2) is still true since count is 1 13

Trace while Loop int count = 0; while (count < 2) { Print Welcome to Java System.out.println("Welcome to Java!"); count++; 14

int count = 0; while (count < 2) { Trace while Loop System.out.println("Welcome to Java!"); count++; Increase count by 1 count is 2 now 15

int count = 0; while (count < 2) { Trace while Loop System.out.println("Welcome to Java!"); count++; (count < 2) is false since count is 2 now 16

Trace while Loop int count = 0; while (count < 2) { The loop exits. Execute the next statement after the loop. System.out.println("Welcome to Java!"); count++; 17

Caution: no equality for reals Don t use floating-point values for equality checking in a loop control - floating-point values are approximations for some values Example: the following code for computing 1 + 0.9 + 0.8 +... + 0.1: double item = 1; double sum = 0; while (item!= 0) { // No guarantee item will be 0 or 0.0 sum += item; item -= 0.1; System.out.println(sum); Variable item starts with 1 and is reduced by 0.1 every time the loop body is executed The loop should terminate when item becomes 0 There is no guarantee that item will be exactly 0, because the floating-point arithmetic is approximated 0.1 is not represented exactly: 0.1 = 1/16 + 1/32 + 1/256 + 1/512 + 1/4096 + 1/8192 +... It is actually an infinite loop! 18

Caution: equality for reals One solution is to use ">= 0": double item = 1; double sum = 0; while (item >= 0) { sum += item; item -= 0.1; System.out.println(sum); 19

do-while Loops do { // Loop body; Statement(s); while (loop-continuation-condition); Statement(s) (loop body) true Loop Continuation Condition? false 20

Why use do while? For when you have a loop body that must execute at 21 least once. For example: a program menu: Scanner in = new Scanner(System.in); String selection; int counter = 0; do{ System.out.println("Choose a Menu Option:"); System.out.println("P) Print Counter"); System.out.println("Q) Quit"); System.out.print("ENTER: "); selection = in.nextline(); if (selection.touppercase().equals("p")) System.out.println("Counter: " + counter++); while(!selection.touppercase().equals("q")); System.out.println("Goodbye!");

22 An Example Session: Choose a Menu Option: P) Print Counter Q) Quit ENTER: P Counter: 0 Choose a Menu Option: P) Print Counter Q) Quit ENTER: A Choose a Menu Option: P) Print Counter Q) Quit ENTER: P Counter: 1 Choose a Menu Option: P) Print Counter Q) Quit ENTER: Q Goodbye!

for Loops for (initial-action; loop-continuation-condition; action-after-each-iteration) { // loop body; Statement(s); int i; for (i = 0; i < 100; i++){ System.out.println( "Welcome to Java!"); Initial-Action i = 0 Loop Continuation Condition? false (i < 100)? false true Statement(s) (loop body) true System.out.println( "Welcome to Java"); Action-After-Each-Iteration i++ 23 (A) (B)

for loops and counting for loops are popular for counting loops through the indices of a string through the indices of an array (later) through iterations of an algorithm Good for algorithms that require a known number of iterations counter-controlled loops 24

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); Declare i 25

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); Execute initializer i is now 0 26

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); (i < 2) is true since i is 0 27

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); Print Welcome to Java 28

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); Execute adjustment statement i now is 1 29

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); (i < 2) is still true since i is 1 30

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); Print Welcome to Java 31

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); Execute adjustment statement i now is 2 32

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); (i < 2) is false since i is 2 33

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); Exit the loop. Execute the next statement after the loop 34

for loops The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each-iteration in a for loop can be a list of zero or more commaseparated statements. for (int i = 0, j = 0; (i + j < 10); i++, j++){ // Do something for (int i = 1; i < 100; System.out.println(i++)); 35

Infinite loops If the loop-continuation-condition in a for loop is omitted, it is implicitly true: for ( ; ; ) { // Do something (a) Equivalent while (true) { // Do something (b) 36

Caution ; Adding a semicolon at the end of the for clause before the loop body is a common mistake: Logic Error for (int i=0; i<10; i++); { System.out.println("i is " + i); 37

Caution ; Adding a semicolon at the end of the while clause before the loop body is also a common mistake: Logic Error int i=0; while (i < 10); { System.out.println("i is " + i); i++; 38

Caution int sum = 0; for (int j=1; j<=4; j++){ sum = sum + j; j++; Be careful not to double the update of your counting variable 39

Which Loop to Use? while, do-while, and for loops are expressively equivalent while (loop-continuation-condition) { // Loop body (a) Equivalent for ( ; loop-continuation-condition; ) // Loop body (b) for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; (a) Equivalent initial-action; while (loop-continuation-condition) { // Loop body; action-after-each-iteration; (b) 40

Using a flag A flag is a boolean loop control boolean moreworkflag = true; int factorial = 1; while (moreworkflag){ factorial *= N; N--; if (N == 1) moreworkflag = false; How does it work? flag used as loop condition inside the loop, test for ending condition when condition is reached, turn flag off once turned off, loop ends 41

Sums int sum = 0; for (int i=1; i<=4; i++) sum = sum + i; sum i 0 1 1 2 3 3 6 4 10 5 10 42

Nested Loops for (int i = 1; i <= 10; i++){ for (int j = 1; j <= 10; j++){ int product = i*j; System.out.print(product + " "); System.out.print("\n"); 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30... 10 20 30 40 50 60 70 80 90 100 43

Local Variables and Blocks A variable declared inside a block is known only inside that block it is local to the block, therefore it is called a local variable when the block finishes executing, local variables disappear references to it outside the block cause a compiler error That includes Init field of for loops: for(int i=0; i < 10; i++){... 44

Java Good programming Practice Do not declare variables inside loops it takes time during execution to create and destroy variables, so it is better to do it just once for loops) 45

Keywords break and continue 46 You can also use break in a loop to immediately terminate the loop: public static void main(string[] args) { int sum = 0; int number = 0; while (number < 20) { number++; sum += number; if (sum >= 100) // increments until the sum is break; // greater than 100 System.out.println("The number is " + number); System.out.println("The sum is " + sum); The number is 14 The sum is 105

Keywords break and continue 47 You can also use continue in a loop to end the current iteration and program control goes to the end of the loop body (and continues the loop): public static void main(string[] args) { int sum = 0; int number = 0; while (number < 20) { // adds integers from 1 to 20 number++; if (number ==10 number == 11) continue; sum += number; // except 10 and 11 to sum System.out.println("The number is " + number); System.out.println("The sum is " + sum); The number is 20 The sum is 189