FIT1002 2006 1 Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.

Slides:



Advertisements
Similar presentations
FIT FIT1002 Computer Programming Unit 19 Testing and Debugging.
Advertisements

Repetition Statements Recitation – 02/20/2009 CS 180 Department of Computer Science, Purdue University.
Computer Science 1620 Loops.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
1 CSE1301 Computer Programming Lecture 10: Iteration (Part 1)
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
1 CSE1301 Computer Programming Lecture 11: Iteration (Part 2)
1 CSE1301 Computer Programming Lecture 10: Iteration (Part 1)
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 (!)
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.
1 CSE1301 Computer Programming Lecture 11: Iteration (Part 2)
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©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.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
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
Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II) Introduction to Computing Lecture 07: Repetition and Loop Statements (Part.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
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 Loops.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
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 4: Control Structures II
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
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.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
Lecture 4 CS140 Dick Steflik. Reading Keyboard Input Import java.util.Scanner – A simple text scanner which can parse primitive types and strings using.
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Control Structures II
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Loop Structures.
Repetition-Counter control Loop
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
CSI 121 Structure Programming Language Lecture 10: Iteration (Part 1)
Arrays, For loop While loop Do while loop
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Control Statements Loops.
Lab5 PROGRAMMING 1 Loop chapter4.
Assist.Prof.Dr. Nükhet ÖZBEK Ege University
Control Statements Loops.
Repetition Statements
Presentation transcript:

FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand nested iteration be able to write simple code with iterations Reading: Savitch, Sec. 3.3

FIT The while Statement Implements the repetition in an algorithm Repeatedly executes a block of statements Tests a condition (Boolean expression) at the start of each iteration Terminates when condition becomes false (zero)

FIT Example: averaging numbers Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count

FIT Initialize Check condition Update Iteration Control Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count

FIT Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; }

FIT Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; }

FIT import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count

FIT Aside: Keyboard Input Java 5 provides a convenient way for simple keyboard input, the Scanner class. you must “import java.util.Scanner;” This makes the Scanner class known to your program. More about this later… You create a new scanner object for a particular input stream (“channel”): Scanner console = new Scanner(System.in); new values can then be read from the Scanner object using – console.nextInt (Integer) – console. nextFloat (Float) – console. nextLine (String) – etc (see Java API doc at Sun’s web site)

FIT import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count Same as: count = count + 1; Decrement: count --; (Savitch, p 30-33)

FIT import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count Other contracted forms: +=, -=, etc we could write: sum += console.nextInt();

FIT import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count The whole block to be repeated is marked by braces { … } unless it is a single statement.

FIT import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count Don’t forget a cast is required to obtain a float division and result. What would happen without it?

FIT Example: averaging maxcountnewIntsum 20???? 0 import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; }

FIT Example: averaging maxcountnewIntsum 20???? import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; }

FIT import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Example: averaging maxcountnewIntsum 20????

FIT import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Example: averaging maxcountnewIntsum 20????

FIT Example: averaging maxcountnewIntsum 2133 import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; }

FIT import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Example: averaging maxcountnewIntsum

FIT import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float avg(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Example: averaging maxcountnewIntsum The loop now terminates as the condition is false and the next statement after the loop is executed (here: return).

FIT Common Mistakes in while – “ one liners” while (num < minimum) num = console.nextInt(); System.out.println(“Number must be greater than “ + minimum); System.out.println(“Please try again.”); while (num < minimum) { num = console.nextInt(); } System.out.println(“Number must be greater than “ + minimum); System.out.println(“Please try again.”);

FIT Common Mistakes in while – “ one liners” while (num < minimum) num = console.nextInt(); System.out.println(“Number must be greater than “ + minimum); System.out.println(“Please try again.”); while (num < minimum) { num = console.nextInt(); System.out.println(“Number must be greater than “ + minimum); System.out.println(“Please try again.”); }

FIT Common Mistakes in while extra semi-colon; Marks the end of the while-block -- usual cause of infinite loops while (num < minimum) ; { num = console.nextInt(); System.out.println(“Number must be greater than “ + minimum); System.out.println(“Please try again.”); }

FIT The for Statement Form of loop which allows for initialization and iteration control Syntax: for ( initialization ; condition ; update ) { instruction block } Careful! A semi-colon here marks the end of the instruction block!

FIT Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count public float averageWithFor(int max) { int count; int sum=0; for (count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)count; }

FIT Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count public float averageWithFor(int max) { int count; int sum=0; for (count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)count; } Initialize

FIT Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count Test Test is performed before the body public float averageWithFor(int max) { int count; int sum=0; for (count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)count; }

FIT Example: averaging Read in numbers, add them, and return their average max is number of numbers to read set sum to 0 set count to 0 while (count < max) { input nextNum add nextNum to sum add 1 to count } return sum/count Update Update is performed after the body public float averageWithFor(int max) { int count; int sum=0; for (count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)count; }

FIT while and for import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float averageWhile(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } public float averageFor(int max) { int count; int sum=0; for (count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)count; }

FIT while and for import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float averageWhile(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Initialize public float averageFor(int max) { int count; int sum=0; for (count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)count; }

FIT public float averageFor(int max) { int count; int sum=0; for (count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)count; } while and for import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float averageWhile(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Test

FIT while and for import java.util.Scanner; public class Test { Scanner console = new Scanner(System.in); public float averageWhile(int max) { int count=0; int sum=0; while (count < max) { int newInt = console.nextInt(); sum = sum + newInt; count ++; } return sum/(float)count; } Update public float averageFor(int max) { int count; int sum=0; for (count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)count; }

FIT For / While Equivalence Every For loop can always be rewritten as a while loop …and vice versa For loops are typically preferred for any form of “counting” (I.e. where the number of iterations is known)

FIT Local Loop Variables You can declare a new counter variable locally for the loop body. Thjs is done in the for initalization (good style!) public float averageWithFor(int max) { int count; int sum=0; for (count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)count; } public float averageWithFor(int max) { int sum=0; for (int count=0; count < max; count++) { int newInt = console.nextInt(); sum = sum + newInt; } return sum/(float)max; }

FIT do-while There is a variant of the while statement, the do-while statement The only difference to the normal while is, when the test is executed while: before loop body do-while : after loop body A do-while body will always be executed at least once. do { int newInt = console.nextInt(); sum = sum + newInt; count ++; } while (count < max)

FIT The break / continue Statements Implements the "exit loop" primitive. Break causes flow of control to leave a loop block ( while or for ) immediately and continue after the loop. Continue ends only the current loop iteration and transfers the control back to the update expression (potentially entering the next iteration of the loop). Style In almost all cases using break and continue is in bad style. They should only be used to terminate a loop in abnormal situations.

FIT Example reciprocal Print out the reciprocals of numbers entered. Quit when 0 is entered loop { input nextNum if (nextNum is 0) { exit loop } else { output 1/nextNum } public void reciprocal() { while (true) { float newFloat = console.nextFloat(); if (newFloat==0) break; else System.out.println( 1/newFloat); } System.out.println("You entered Zero!"); }

FIT Example reciprocal Print out the reciprocals of numbers entered. Quit when 0 is entered loop { input nextNum if (nextNum is 0) { exit loop } else { output 1/nextNum } public void reciprocal() { while (true) { float newFloat = console.nextFloat(); if (newFloat==0) break; else System.out.println( 1/newFloat); } System.out.println("You entered Zero!"); } “while (True)” infinite loop

FIT Infinite Loops while ( true ) {...etc...etc...etc... } for ( ; true ; ) {...etc...etc...etc... } for ( ; ; ) {...etc...etc...etc... } Use an: if ( condition ) { break; } statement to break the loop

FIT Example Factorization Write a program which prints out the prime factorization of a number (treat 2 as the first prime) For example, on input 6, desired output is: 2 3 " " 24, " " : " " 14, " " : 2 7 " " 23, " " : 23 ( 23 is prime)

FIT input n set factor to 2 Algorithm

FIT input n set factor to 2 while(some factor yet to try) { } Algorithm (cont)

FIT input n set factor to 2 while(some factor yet to try) { if (n is divisible by factor) { output factor set n to n / factor } } Algorithm (cont)

FIT input n set factor to 2 while(some factor yet to try) { if (n is divisible by factor) { output factor set n to n / factor } else { increment factor } Algorithm (cont)

FIT input n set factor to 2 while(some factor yet to try) { if (n is divisible by factor) { output factor set n to n / factor } else { increment factor } Example: factorize public void factorize(int number) { int factor=2; while (number > 1) { if (number % factor == 0) { System.out.println(factor); number = number / factor; } else factor++; }

FIT Iterating over a String (For) Many string algorithms require iteration over the characters in a string. The for loop is ideally suited to do this. The characters in a string can be accessed by position index using the charAt method. Indices run from 0 to length -1! char charAt(int index) The length of the string can be obtained with the length method int length()

FIT Example: CountConsonantsAndVowels Count the number of consonants and the number of vowels in a file Non-alphabetic characters should not be counted

FIT input String set consonantCount to 0 set vowelCount to 0 loop over all characters in the string { set ch as next character in string if (ch is a vowel) { increment vowelCount } else if (ch is a consonant) { increment consonantCount } output consonantCount, vowelCount Algorithm: count consonants and vowels

FIT public void stringCount() { String s = console.nextLine(); int vowels=0; int consonants=0; for (int i=0; i< s.length(); i++) { char c = s.charAt(i)); c = Character.toLowerCase( c ); if (Character.isLetter( c )) if (c=='a' || c=='e' || c=='i' || c =='o' || c=='u') vowels ++; else consonants++; }// for loop ends here System.out.println(s+" has”+ vowels+" Vowels and "+ consonants+" Consonants."); } Note the use of the service functions in the Character class. Try to find these in the API definition on the web! input String set consonantCount to 0 set vowelCount to 0 loop over all characters in the string { set ch as next character in string if (ch is a vowel) { increment vowelCount } else if (ch is a consonant) { increment consonantCount } output consonantCount, vowelCount

FIT Iterating over a String (While) Re-write the stringCount Method with a while loop instead of a for loop

FIT Nested Loops Loops can be placed inside other loops The break statement applies to the innermost enclosing while or for statement

FIT Example: rectangle Print an m by n rectangle of asterisks input width and height for each row { for each column in the current row { print an asterisk } start next row } public void rectangle(int width, int height) { for (int row=1; row <= height; row++) { for (int column=1; column <= width; column++) System.out.print("*"); System.out.println(); }

FIT Nested Loops: Loop Dependencies An inner loop can depend on an outer (enclosing) loop. How would you modify “rectangle” into a method to print a triangle? Modify this to print a triangle of asterisks input width and height for each row { for each column in the current row { print an asterisk } start next row } * ** *** **** ***** ****** ******* ******** ********* **********

FIT Example: triangle Print an m row triangle of asterisks input height for each row { for each column in the current row { print as many asterisk as the number of the row } start next row }

FIT Example: triangle Print an m row triangle of asterisks input height for each row { for each column in the current row { print as many asterisk as the number of the row } start next row } public void triangle(int height) { for (int row=1; row <= height; row++) { for (int column=1; column <= row; column++) System.out.print("*"); System.out.println(); }