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

Similar documents
Loops. CSE 114, Computer Science 1 Stony Brook University

Computer Programming I - Unit 5 Lecture page 1 of 14

Problem Solving With Loops

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.

ECE 122. Engineering Problem Solving with Java

Repetition, Looping. While Loop

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

Example: Monte Carlo Simulation 1

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

Lecture 7 Tao Wang 1

CS1150 Principles of Computer Science Loops (Part II)

COMP 202 Java in one week

Repetition Structures

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

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

switch-case Statements

REPETITION CONTROL STRUCTURE LOGO

COMP 202. Java in one week

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

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

Flow of Control. Chapter 3 Part 3 The Switch Statement

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

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

Increment and the While. Class 15

CMPT 125: Lecture 4 Conditionals and Loops

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

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

Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way

Repetition, Looping CS101

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

++x vs. x++ We will use these notations very often.

AP Programming - Chapter 6 Lecture

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

Flow of Control: Loops

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

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

Why Is Repetition Needed?

Arithmetic Compound Assignment Operators

Java Coding 3. Over & over again!

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Chapter 5: Loops and Files

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Flow of Control: Loops. Chapter 4

CompSci 125 Lecture 11

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

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

More on control structures

Flow of Control: Loops

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

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

Iteration statements - Loops

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

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

Control Structures of C++ Programming (2)

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

CS1004: Intro to CS in Java, Spring 2005

FLOW CONTROL. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

Programming for Engineers Iteration

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

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

Midterm Examination (MTA)

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

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

! 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

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

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

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

Flow of Control: Loops. Objectives. Java Loop Statements: Outline 6/27/2014. Chapter 4

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

IST 297D Introduction to Application Programming Chapter 4 Problem Set. Name:

1 Short Answer (10 Points Each)

Computing Science 114 Solutions to Midterm Examination Tuesday October 19, In Questions 1 20, Circle EXACTLY ONE choice as the best answer

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

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

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Chapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Flow Control. CSC215 Lecture

Introduction. Pretest and Posttest Loops. Basic Loop Structures ว ทยาการคอมพ วเตอร เบ องต น Fundamentals of Computer Science

Chapter 5: Control Structures II (Repetition)

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

AP Computer Science A

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

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

4. Flow of Control: Loops

4. Flow of Control: Loops. Objectives. Java Loop Statements 10/10/12. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich

Over and Over Again GEEN163

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

Chapter 8 Statement-Level Control Structures

CS 101 Spring 2007 Midterm 2 Name: ID:

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

Transcription:

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

Iteration: While Loops Pretest loop Most general loop construct Only loop construct needed Syntax: while (<boolean_expression>) <statement> Note the similarity to the if statement Semantics: Example: //Count from 1 to 10 int i = 1; while (i < 11){ System.out.println(i); i++; 2

Iteration: Potential Problems 1. Infinite loop Loop that never ends Can result due to many reasons: Failure to update LCV Failure to update LCV properly Poor choice of termination condition Failure to update process 2. Off-by-one error Count-controlled loop that iterates one too many or one too few times 3

Iteration: Loop-and-a-half Construct In some situations, makes sense to halt loop execution in middle of loop This referred to as loop-and-a-half control No specific loop construct that implements this Implemented via a break statement Syntax: break; Semantics: Control passes to statement following containing control statement Example: //Check that values are within range Scanner scnr = new Scanner(System.in); int next, count = 0; boolean badinput = false; while (count < 100) { if ((next < 50) (next > 75)) { badinput = true; break; count++; if (badinput) System.out.println("Invalid input at position " + count); else System.out.println("All input valid"); 4

Example without break: Iteration: Loop-and-a-half Construct //Check that values are within range Scanner scnr = new Scanner(System.in); int next, count = 0; boolean badinput = false; while ((count < 100) &&!badinput){ if ((next < 50) (next > 75)) { badinput = true; else count++; if (badinput) System.out.println("Invalid input at position " + count); else System.out.println("All input valid"); Problems: 1. Potential infinite loop 2. More difficult to debug as now have multiple exit points 5

Iteration: Do-while Loops Post test loop Syntax: do <statement> while (<Boolean_expression>); Semantics: Body must execute at least once Example: //Error check input Scanner scnr = new Scanner(System.in); int next; do { if ((next < 75) (next > 100)) { System.out.println(next + " is invalid"); System.out.println("Enter a value between 75 and 100"); while ((next < 75) (next > 100)); Example: Corresponding while loop with priming read //Error check input Scanner scnr = new Scanner(System.in); int next; while ((next < 75) (next > 100)) { System.out.println(next + " is invalid"); System.out.println("Enter a value between 75 and 100"); 6

Iteration: For Loops Pre test loop Works same as while Intended for count-controlled looping Loop control handled automatically in header Syntax: for ([<initializers>];[<continuation_condition>];[<updates>]) <statement> where < initializers > is a comma-separated list that initializes variables (including the LCV) < continuation condition > halts the iteration when false < updates > modify variables in < initializers > Semantics: v1 = expression1; //variables in <initializers> v2 = expression2;... while (<continuation_condition>) { statement v1 = update_expression1; v2 = update_expression2;... Usually only a single variable (LCV) appears in <initializers> and <updates> If <continuation condition> omitted, defaults to true 7

Example: Basic count control Iteration: For Loops (2) //Basic count control: Average n integers. int limit, sum; limit = 10; sum = 0; for (int counter = 0; counter < limit; counter++) { number = (int) ((Math.random() * 100) + 1); sum += number; System.out.println("The average = " + (float) sum / limit); Example: Basic count control //Basic count control: Counting backwards by 2 s int max, counter; max = (int) (Math.random() * 101); for (counter = max; counter >= 0; counter = counter - 2) System.out.println("Counter = " + counter); LCV declared in for header is local to loop body: int i = 10; for (int i = 0; i < 5; i++) System.out.println("i = " + i"); System.out.println("i = " + i"); vs int i = 10; for (i = 0; i < 5; i++) System.out.println("i = " + i"); System.out.println("i = " + i"); 8

Iteration: For Loops (3) continue statement Syntax: continue; Semantics: Control jumps to end of loop without exiting loop Example: // Display even integers for (int counter = 0; counter < 100; counter++) { if (counter % 2 == 1) continue; System.out.println(counter); 9