Loops. Repeat after me

Similar documents
Control structures in C. Going beyond sequential

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

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

Chapter 4: Control structures. Repetition

Chapter 4: Control structures

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

Loops / Repetition Statements

Java Classes: Math, Integer A C S L E C T U R E 8

Building Java Programs

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

Java Coding 3. Over & over again!

STUDENT LESSON A12 Iterations

AP Computer Science Unit 1. Programs

Repetition Structures

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Problem Solving With Loops

Repetition and Loop Statements Chapter 5

Repetition, Looping. While Loop

Example: Monte Carlo Simulation 1

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

Iteration statements - Loops

Repetition. Chapter 6

Midterm Examination (MTA)

Repetition. Chapter 6

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

CS111: PROGRAMMING LANGUAGE II

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

Control Structures II. Repetition (Loops)

Controls Structure for Repetition

CS141 Programming Assignment #6

CompSci 125 Lecture 11

CSC 1051 Data Structures and Algorithms I

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

Flow of Control: Loops. Chapter 4

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

Building Java Programs

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

Programming with Java

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Problem 7.4: Racetrack

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

! 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

Introduction to Computer Science Unit 2. Exercises

Over and Over Again GEEN163

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

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

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

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

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

Chapter 3. Selections

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Control Statements: Part 1

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

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

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

1 Short Answer (5 Points Each)

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

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

Darrell Bethea May 25, 2011

CS 112 Introduction to Programming

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

Introduction to Computer Programming

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

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

Computer Programming I - Unit 5 Lecture page 1 of 14

REPETITION CONTROL STRUCTURE LOGO

COMP-202 Unit 4: Programming with Iterations

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

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

CS141 Programming Assignment #8

Logic & program control part 2: Simple selection structures

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

AP CS Unit 3: Control Structures Notes

Selection and Repetition Revisited

Loops. Repeat after me

Logic & program control part 3: Compound selection structures

Java Programming Language. 0 A history

CMPT 125: Lecture 4 Conditionals and Loops

Principles of Computer Science I

204111: Computer and Programming

Top-Down Program Development

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

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

CS111: PROGRAMMING LANGUAGE II

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Introduction to the Java Basics: Control Flow Statements

Tasks for fmri-setting (Tasks of first and second pilot study at the end)

What two elements are usually present for calculating a total of a series of numbers?

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Transcription:

Loops Repeat after me

Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements repeat is determined by the value of a control variable, which is tested at the beginning of each loop iteration

Count control vs. event control Count control uses automatic increment (or decrement) of control variable to update its value and stop loop Event control requires intervention (input) to change control variable s value and stop loop

Java syntax for a while loop // initialize control variable - e.g. int x = 0; while (control variable not equal to final value) { // statements that repeat a process // statement or statements that update control variable NOTE: Loop body can be a single statement, a null statement, or a block.

Example int x = 0; // control variable initialization while (x < 100) // control variable test { System.out.printf ( x=%d\n, x); x ++; // control variable updated

While Statement while ( Expression ) { statement(s); Expression is test for terminating condition Loop exit occurs when test succeeds (tests false) Loop entry is moment flow of control reaches 1st statement in loop body One iteration means one pass through the loop Even though actual value being tested changes inside loop body, exit does not occur until next time value is tested

Count-controlled loop example public class countdown { public static void main(string [] args) { int x = 10; while (x > 0) { System.out.printf( %2d\n, x); x--; System.out.println( Lift off! ); Loop trace: Value of x Output 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 (loop ends) Lift off!

int sum = 0, number = 1; Example while ( sum <= 1000000 ) { sum = sum + number; number = number + 1; When will the loop end? A.When number reaches 100 B.When sum equals 1000000 C.When number exceeds 100 D.When sum exceeds 1000000

Example int product = 1, number = 1, count = 20, lastnumber; lastnumber = 2 * count - 1; while (number <= lastnumber) { product = product * number; number = number + 2; When the loop concludes, what is the value of number?

Example: finding sum and average 100 numeric values need to be added together and averaged Using a while loop: read the 100 values find their total find their average

Scanner kb = new Scanner(System.in) ; int thisnum; int total = 0; // initialize sum int count = 0; // initialize loop control while ( count < 100 ) // test expression { System.out.print ( Enter value: ); thisnum = kb.nextint(); // read 1 value total = total + thisnum ; // add value to sum count++ ; // update loop control System.out.println ( The sum of the values is: + total); System.out.println ( The average is: + (double)total/count);

Event-controlled Loops: examples of events Sentinel value trigger keep processing data until a special value which is not a possible data value is entered to indicate that processing should stop End-of-input trigger keep processing data as long as there is more data to be read Flag value trigger keep processing data until the value of a flag changes in the loop body because of abnormal data

Examples of Kinds of Loops Count controlled loop Read exactly 100 values. End-of-input controlled loop Read all the values no matter how many are there; check for end of data

Examples of Kinds of Loops Sentinel controlled loop Read values until a special value (like -1) selected by you is read. Flag controlled loop Read values until a value outside the expected range (say, 200 or more) is read.

A Sentinel-controlled Loop requires a priming read priming read means you read one set of data before the while

Sentinel-controlled loop Priming read occurs before loop body The value being processed in the loop body is the value that was read in the previous iteration The last action in the loop body is to read the next value When the sentinel value is read, the loop test will fail and the loop will stop

// Sentinel controlled loop Scanner kb = new Scanner(System.in); int total = 0; int thisnum; // priming read System.out.print( Enter a positive number (-1 to stop ): ; thisnum = kb.nextint(); while (thisnum!= -1) { // while last value read is not sentinel total = total + thisnum; System.out.print( Enter a positive number (-1 to stop ): ; thisnum = kb.nextint(); System.out.println ( Total sum is: + total);

// End-of-input controlled loop Scanner file = new Scanner(new FileInputStream ( data.txt )); int thisnum, total = 0; while (file.hasnext()){ thisnum = file.nextint(); total = total + thisnum; file.close(); System.out.println( Total of values read is: + total); This type of loop is typical when input is read from a file. Note that the look-ahead method (hasnext()) eliminates the need for a priming read

Loop applications We have already seen some common applications of loops, including: reading and performing calculations (such as finding a sum) on a set of data values processing a set of data to find a concluding value (finding an average, finding the greatest common divisor) Other applications include: data validation keeping track of occurences of particular values in a data set

Example: Data Validation Scanner kb = new Scanner (System.in); int age; System.out.print( Enter your age (between 0 and 130):"); age = kb.nextint(); while (age < 0 age > 130) { System.out.println ("An invalid age was entered. Please try again."); System.out.print ( Enter your age (between 0 and 130):"); age = kb.nextint();

Example: counting occurrences Scanner kb = new Scanner(System.in); int num, // random number factor, // factor to find multiples of howmany, // number of random values to generate lcount = 0, // loop counter ocount = 0; // occurrence counter Random rg = new Random(); System.out.print ( How many tries?: ); howmany = kb.nextint(); System.out.print ( Enter numeric factor to look for: ); factor = kb.nextint(); while (lcount < howmany) { num = Math.abs (rg.nextint()); if (num % factor == 0) ocount++; lcount++; System.out.println ( There were + ocount + multiples of + factor + in this set of + howmany + random numbers. );

Watch Out for Pitfalls 1. Watch out for the off-by-one error (OBOE). 2. Make sure the loop body contains a statement that will eventually cause the loop to terminate. 3. Make sure the loop repeats exactly the correct number of times. 4. If you want to execute the loop body N times, then initialize the counter to 0 and use the test condition counter < N or initialize the counter to 1 and use the test condition counter <= N.

Which loop executes exactly 10 times? 1 count = 1; count = 1; while ( count < 10 ){ while ( count <= 10 ){...... count++; count++; 2

Which loop executes exactly 10 times? 1 count = 0; count = 0; while ( count <= 10 ){ while ( count < 10 ){...... count++; count++; 2

Overflow An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold. In Java, an overflow does not cause program termination: With types float and double, a value that represents infinity is assigned to the variable With type int, the value wraps around and becomes a negative value

Loop Design - considerations What process is repeated? How is process initialized & updated? What condition ends loop? How is condition initialized? How is condition updated? What is state of program upon loop exit?

Loop ending condition -- designing flow of control Can usually determine condition by looking at the problem statement Initialization: assignment (e.g. for count control) priming read (for event) Update autoincrement vs. input

Designing loop process Decide what a single iteration will do May need to initialize variables before loop body and update their values within loop body Examples accumulating a sum keeping a running tally

Program state on loop exit All variables involved in the loop will have values at exit Need to initialize variables with care to avoid off-by-one errors

Loop design example Write a program that reads in text file and reports the number of lines, letters and capital letters read What type of loop control? What is stop condition? What variables are needed & how should they be initialized?