ITERATION CSC 171 FALL 2004 LECTURE 10. Simple Branching If (test){ A;} start end A; test.

Slides:



Advertisements
Similar presentations
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Advertisements

©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
Computer Science 1620 Loops.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
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.
For Loops & Iterators CSC 171 FALL 2001 LECTURE 7.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
General Announcements Project Due Friday, 1/30 Labs start Wednesday & Thursday – Java review – Weiss 1.19, 1.20 – You may show up & hand in Workshops.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
SELECTION CSC 171 FALL 2004 LECTURE 8. Sequences start end.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Java Programming: From the Ground Up
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Chapter 5 Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Repetition Statements while and do while loops
Chapter 5: Control Structures II
If Statement if (amount
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
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.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lecture 4b Repeating With Loops
Chapter 5: Control Structures II
Loop Structures.
Selected Topics From Chapter 6 Iteration
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Repetition Statements (Loops) - 2
Repetition Statements
Loop Invariants CSC 171 FALL 2001 LECTURE 6.
CSS161: Fundamentals of Computing
Loops CGS3416 Spring 2019 Lecture 7.
Presentation transcript:

ITERATION CSC 171 FALL 2004 LECTURE 10

Simple Branching If (test){ A;} start end A; test

“Backward” Branching while(test){ A;} A; start end test

Example what is the output? int x = 3; int sum = 0; while (x > 0) { sum = sum + x; x = x – 1; System.out.print(“x == “ + x); System.out.println(“sum == “ + sum); } x == 3, sum = 0 x == 2, sum = 3 x == 1, sum = 5 x == 0, sum = 6

Example what is the output? int x = 3; int sum = 0; while (x < 5) { sum = sum + x; x = x – 1; System.out.print(“x == “ + x); System.out.println(“sum == “ + sum); } x == 3, sum = 0 x == 2, sum = 3 x == 1, sum = 5 x == 0, sum = 6 x == -1, sum = 6 ……

Infinite Loops A very common fault in program design System compiles ok Then appears to “hang”

Shorthand Operators a = a + b ; a = a – b; a = a * b; a = a / b; a = a % b a += b; a -= b; a *= b; a /= b; a %= b;

More Shorthand int x; x = x + 1; x += 1; x = x – 1; x -= 1; x++; x-- ;

Shorthand Operators “x++;” vs. “++x” int x = 0; System.out.println(“x == “ + x++); System.out.println(“x == “ + ++x); System.out.println(“x == “ + x--); System.out.println(“x == “ + --x); x==0 x==2 x==0

Loop invariants Intro to mathematical program analysis In order to verify loops we often establish an assertion (boolean expression) that is true each time we reach a specific point in the loop. We call this assertion, a loop invariant

Assertions When ever the program reaches the top of the while loop, the assertion is true INIT BODY TEST INVARIANT

Example Write a method to compute a n public static int power(int a, int n) Positive values only ok You have 5 minutes

Possible solution public static int power(int a, int n) { int r = 1; int b = a; int i = n ; while (i>0){ r *= b; } return r; }

Possible solution (Euclid) public static double power(int a, int n) { int r = 1; int b = a; int i = n ; while (i>0) { if (i%2 == 0) { b = b * b; i = i / 2;} else { r = r * b; i--; } } return r; }

Does it work? SURE! TRUST ME! Well, look at a 100 if you don’t believe me! – Note, less loops! Can you “prove” that it works? bir a1001 a2a2 50 a4a a4a4 a8a8 12 a 16 6 a a 36 a a 100

What is the loop invariant? At the top of the while loop, it is true that r*b i = a n It is? – Well, at the top of the first loop r==1 b==a i==n

So, if it’s true at the start Even case r new = r old b new == (b old ) 2 i new ==(i old )/2 Therefore, r new * (b new ) inew == r old * ((b old ) 2 ) iold/2 == r old * (b old ) iold == a n

So, if it’s true at the start II Odd case r new = r old *b old b new == b old i new ==i old -1 Therefore, r new * (b new ) inew == r old *b old * (b old ) iold-1 == r old * (b old ) iold == a n

So, If it’s true at the start And every time in the loop, it remains true Then, it is true at the end r*b i = a n And, i == 0 ( the loop ended) What do we know?

Correctness Proofs Proof are more valuable than testing – Tests demonstrate limited correctness – Proofs demonstrate correctness for all inputs For some time, people hoped that all formal logic would replace programming The naïve idea that “programming is a form of math” proved to be an oversimplification

Correctness Proofs Unfortunately, in practice, these methods never worked very well. – Instead of buggy programs, – people wrote buggy logic Nonetheless, the approach is useful for program analysis

The take away message? In the end, engineering and (process) management are at least as important as mathematics and logic for the successful completion of large software projects

Do while A useful variant of the while loop

“Backward” Branching while(test){ A;} A; start end test

“Backward” Branching do { A; }while (test); A; start end test

YOU WRITE THE CODE start end y < 3 X = 1; y = 1; X = 2 * x; y++;

Use of a sentinel A variable that “keeps track” of the ending condition

Example static int myGetInt() { boolean done = false; String locIn = ""; int returnVal = 0; InputStreamReader reader = new InputStreamReader(System.in); BufferedReader console = new BufferedReader(reader); //sentinal

do { try { locIn = console.readLine(); returnValue = Integer.ParseInt(locIn); done = true; } catch (Exception e) { System.out.println(e + “trouble"); done = false; } } while (!done); return returnVal; } Problems here are caught here

For loops Sometimes, we want the loop to repeat for a set (definite) number of times. A type of while loop That became so common It was given it’s own syntax

TYPES OF ITERATION Indefinite Iteration: – We don’t know exactly how many times we want the loop to repeat – “while” loop Definite Iteration – We know how many time we want the loop to repeat – “for” loop

While loop

While loop Code int year = 0 ; while (balance < 2 * initialBalance){ balance += balance * interest; year++; }

Example of a “for” loop as a while int count ; count = 0; while(count < 10) { A;count++;} A; start end count<10 count++ count=0

Example of a “for” loop as a for for(int count = 0; ;count < 10; ;count < 10; count++;) { count++;) {A;} A; start end count<10 count++ count=0

Generic “for” loop for(init; test ; update;) { update;) {body;} body; start end test update init

For loop

For loop Code for (int year = 1;year<=20;year++){ balance += balance * interest; }

For Loop Initialization Test Body Increment for(initialzation;test;increment){ //Body }

Off by one errors If you want n iterations Start at 0 and go to x < n Or Start at 1 and go to x <= n

Nested Loops Sometimes, we want to perform 2D operations Tables – Addition – Multiplication – Interest rates

Multiplication Table What is the output? int size = 5; for(int i = 0 ; i<size;i++) { for(int j = 0 ; j<size;j++) { System.out.println(String.toString(i*j)); }

Multiplication Table Fixed int size = 5; for(int i = 0 ; i<size;i++) { for(int j = 0 ; j<size;j++) { System.out.print(String.toString(i*j) + “ “); } System.out.println(); }

Enumerations Integers are nice, because we always have a clear idea of what the next one is. But sometimes, we have an orderd set or list of things that aren’t numbers – {Hearts, Spades, Diamonds, Clubs} – {Bob, Carol, Ted, Alice} We would like to go through them one at a time

public interface Enumeration An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series. For example, to print all elements of a vector v:

General Case Enumeration e ; while(e.hasMoreElements()) { System.out.println(e.nextElement( )); }

Our Fave: StringTokenizer A String Tokenizer breaks strings up into tokens (surprize!) String “Hello CSC 171, How are you” Tokens: – “Hello”,“CSC”,”171,”,”How”,”are”,”you” StringTokenizer tokenizer = new StringTokenizer(inputLine);

Using String Tokenizer import java.util.StringTokenizer; public class Split { public static void main(String[] args){ boolean done = false; while (!done){ String inputLine = myGetString(); if (inputLine == null) done = true; else { // break input line into words

String Tokeizer II StringTokenizer tokenizer = new StringTokenizer(inputLine); while (tokenizer.hasMoreTokens()){ String word = tokenizer.nextToken(); System.out.println(word); } }}}}