REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.

Slides:



Advertisements
Similar presentations
Control Structures. Decision Making Structures The if and if…else are all selection control structures that introduce decision-making ability into a program.
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.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
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 (!)
Repetition Statements repeat block of code until a condition is satisfied also called loops Java supports 3 kinds of loops: while statement – repeats a.
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
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.
Copyright © Texas Education Agency, Computer Programming For Loops.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Loops and Iteration for Statements, while Statements and do-while Statements.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Grouping objects Introduction to collections 5.0.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Repetition Control Structure. Introduction Many applications require certain operations to be carried out more than once. Such situations require repetition.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
1 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for-each PROS easy to use access to ALL items one-by-one ability to change the state.
Topic : While, For, Do-While Loop Guided By : Branch : Batch :
for-each PROS CONS easy to use access to ALL items one-by-one
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
Lecture 6 Repetition Richard Gesick.
The switch Statement, and Introduction to Looping
Lecture 7: Repeating a Known Number of Times
Loop Structures.
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
CiS 260: App Dev I Chapter 4: Control Structures II.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Arrays, For loop While loop Do while loop
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Outline Altering flow of control Boolean expressions
Computing Fundamentals
Repetition Statements
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Presentation transcript:

REPETITION CITS1001

Scope of this lecture Repetition for loops while loops 2

Iteration fundamentals We often want to repeat some actions over and over e.g. “do this action for each student in the university” e.g. “do this action seventeen times” e.g. “do this action until this condition is true” Java loops provide us with a way to control how many times we repeat these actions The first paradigm above is done by the for-each loop The second paradigm is done by the for loop The third paradigm is done by the while loop 3

Pseudo-code for(initialization; condition; post-body action) { statements to be repeated } General form of the for loop General form of the while loop initialization; while(condition) { statements to be repeated } 4

Equivalent in while-loop form Java examples for(int count = 0; count < 100; count++) { System.out.println(“I can count to: " + count); } int count= 0; while(count < 100) { System.out.println(“I can count to: " + count); count++; } for loop version 5

The for loop The for loop is the most frequently-used looping structure for ( ; ; ) { … } The body of the loop is the collection of statements in the curly brackets 6 The header of the loop is the information in the round brackets

Header – the initialization part The initialization part consists of any Java statement It is performed once only when execution first reaches the for loop It is normally used to initialize a counter variable AKA the index variable 7

Header – the boolean-expression part The boolean expression controls whether or not the body of the loop is executed The expression is evaluated immediately after initialization And at the start of every subsequent iteration If its value is true, then the statements in the body of the loop are executed If its value is false, then the loop has finished and the statements in the body are NOT executed Execution continues at the first statement after the for loop 8

Header – the post-body update The post-body update is a Java statement that is executed once each time the body of the for loop is executed It is executed immediately after the last statement of the body has been executed It is usually used to update the counter variable 9

Is the boolean expression true? The for loop Initialization Body Post-body update No Yes Before loop After loop 10

The for loop idiom for -loops are most often used when we want to do something a specific number of times for (int i=0; i<5; i=i+1) { System.out.println(i); } System.out.println is a library method that prints its argument to the terminal window 11

How did this work? Initialization creates i and sets it to 0 Check if i < 5, yes Print out i – causes 0 to appear on terminal window Update i from 0 to 1 Check if i < 5, yes Print out i – causes 1 to appear on terminal window Update i from 1 to 2 Check if i < 5, yes Print out i – causes 2 to appear on terminal window Update i from 2 to 3 Check if i < 5, yes Print out i – causes 3 to appear on terminal window Update i from 3 to 4 Check if i < 5, yes Print out i – causes 4 to appear on terminal window Update i from 4 to 5 Check if i < 5, NO 12 First iteration Second iteration

The increment operator The post-body update so often consists of i = i+1 ; that there is a short-hand notation for this operation The statement i=i+1 may be replaced simply by i++ for (int i=0; i<5; i++) { System.out.println(i); } In fact i++ is both a statement and an expression As an expression it has the value of i after the incrementing Warning: Use either i=i+1; or i++; but never mix them together and use i=i++; 13

A one-statement body If the body consists of only one statement, then you can leave out the braces, but it is good style to always include them for (int i=0; i<10; i++) { System.out.println(i*i); } is the same as for (int i=0; i<10; i++) System.out.println(i*i); You have been warned! Many hard-to-trace bugs arise from leaving out the brackets in a statement-block 14

Common mistake A surplus semicolon! (this mistake is hard to track down) int i; for (i=0; i<10; i++) ; { System.out.println(i*i); } The output from this code is just 100 Why? What went wrong with the loop? There was a problem with the body 15

int i; for (i=0; i<10; i++) ; { System.out.println(i*i); } int i; for (i=0; i<10; i++) { System.out.println(i*i); } Common mistake The first loop has an empty body (just a single semicolon!), while the second shows the “desired” body 16

Making tables Another common use of for loops is to produce tables Suppose you are asked to produce a temperature conversion table listing the Fahrenheit equivalents of 0–100C in increments of

A for loop is the solution int celsius; int fahrenheit; for (celsius=0; celsius <= 100; celsius = celsius + 5) { fahrenheit = 32 + celsius*9/5; System.out.print(celsius); System.out.print(“ “); System.out.println(fahrenheit); } Notice : the easy-to-read variable names Notice: the use of System.out.print() to print things without starting a new line 18

A numerical example It is known that Suppose we wish to approximate  using this formula There are two ways that we can do it Approximate using a fixed number of terms Approximate to within a certain accuracy The first way is best done using a for loop   = 4 (1 – 1/3 + 1/5 – 1/7 + 1/9 – … ) 19

 to a fixed number of terms public double pi(int n) { double approx = 0; double mult = 4; for (int i=0; i<n; i++) { approx = approx + mult/(2*i+1); mult = -mult; } return approx; } 20

Situation at top of loop imult2*i+1approx Loop stops when i reaches the requested value 21

for loops with bigger steps // Print multiples of 3 up to 40 for(int num = 3; num < 40; num = num + 3) { System.out.println(num); } 22

Review For loops are used when the number of repetitions is known in advance For loops are used when an index variable is required For loops have a regular step-size For-each loops are less error-prone than for loops So use a for-each loop unless you need access to indices or step-size 23

The while loop The third paradigm for repetition is “do this action until this condition is true” We don’t know in advance how many iterations there will be In Java this is done with a while loop We use a boolean condition to decide whether or not to keep going 24

While loop pseudo code while(loop condition) { loop body } while we wish to continue, do the things in the loop body boolean test while keyword Statements to be repeated Pseudo-code expression of the actions of a while loop General form of a while loop 25

Is the boolean expression true? The while loop Body No Yes Before loop After loop 26

Looking for your keys while(the keys are missing) { look in the next place } or while(not (the keys have been found)) { look in the next place } 27

Looking for your keys boolean searching = true; Location place = firstPlace; while(searching) { if(the keys are at place) searching = false; else place = next(place); } But suppose we don’t ever find them? 28

 to a fixed number of terms public double pi(double accuracy) { double approx = 0; double mult = 4; double denom = 1; while (Math.abs(mult / denom) > accuracy) { approx = approx + mult / denom; mult = -mult; denom = denom + 2; } return approx; } 29

Situation at top of loop Stepdenommult/denomapprox Loop stops when the next term is smaller than accuracy 30

Elements of the while loop We have effectively declared an index variable In this case, denom The index variable must be incremented explicitly It’s not updated automatically in the header, as with the for loop The condition must be expressed correctly 31

Searching a collection int index = 0; boolean found = false; while(index < files.size() && !found) { String file = files.get(index); if(file.contains(searchString)) { // We don't need to keep looking. found = true; } else { index++; } // Either we found searchString at index, // or we searched the whole collection, // in which case found = false and index = files.size() 32

Indefinite iteration Does this search still work if the collection is empty? Yes! The loop’s body won’t be entered in that case This is an important feature of while: The body will be executed zero or more times 33

for-each versus while for-each: Easier to write Safer: it is guaranteed to stop while: We don’t have to process the whole collection Doesn’t even have to be used with a collection Take care: could be an infinite loop 34

Review Loop statements allow a block of statements to be repeated The for-each loop allows iteration over a whole collection The for-loop allows bounded iteration a fixed number of times The while-loop allows indefinite iteration when you don’t know how many times a loop will be repeated 35