CS 110 Notes – Repetition 1 Copyright C. Tanner 2010 • Repetition/Iteration/Looping o Repeat ………End o Ability to repeat a set of statements Called the loop body Stop repeating • Set number of times o Counted loop o Iterates through a series of values • Condition is reached o Input matches a sentinel o Counter limit is reached o JAVA has three types of loops For --- iterates thru a series of values • Used for counted loop While – based on condition • Executes the statements in the loop body “while” the condition is true • Executes the loop body 0 or more times Do – based on a condition • Executes the loop body while condition is true • Executes the loop body 1 or more times o Infinite Loops Occur when the stopping condition is never reached Can occur on any loop type • Counted loop o Repeats the loop body a set # of times o Examples Determine grades for an entire class • # of students in the class Calculate baseball statistics • # of players on the team Spin roulette wheel 5 times Find the largest of 10 values Average length of 5 words o Require a counter variable Initialize the counter variable Test – have we reached the set number of times Execute the loop body Increment the count variable • for (counter =initalValue; Condition; Increment) { Statements in the loop body }CS 110 Notes – Repetition 2 Copyright C. Tanner 2010 • for (int i =0; i<5;i++) { System.out.println(i); } • for (int i=5; i>0; i++) { System.out.println(i); } • Sum of 5 values int nextNum; int sum =0; for (int i = 0; i<5; i++) { nextNum= sc.nextInt(); sum += nextNum; } System.out.println(“the sum of the values is: “ + sum); • Write a loop that displays each even integer between 4 and -6 with commas between them for (int i=4; i>=-6;i-=2) { System.out.println (i + “,”); } When we “run” this we see there is a trailing comma, rewrite this so as to remove the trailing comma • Infinite Counted loops • for (int i =1; i>0; i++) – condition is always true and will never become false • for (int i=0; i<10; i--) – simple typo should have been i++ • Using the counter variable outside the loop body o When declared within the for loop statement for (int i =0 …) It can not be used outside the loop body because its scope exists only within the loop body {}CS 110 Notes – Repetition 3 Copyright C. Tanner 2010 • Declare outside of for loop statement int i; for (i=0; i<10; i++) { } if (i==11) i exists since it was declared outside the loop body and can be referenced as such • Sample Programs Words.java, Roulette.java, Largest.java • Event Controlled loops o Counted loop – executes a set number of times and uses a counter variable to keep track of the number of times Can also use the counter variable within the loop to iterate through a set of values o Event controlled loop is based on a condition and looping continues while the condition evaluates to true, once the condition evaluates to false we exit the loop o Event controlled loop can be used to create counted loops as well o While statement while (condition) { Statements – loop body } Test the condition If true execute the body • Since we test the condition *first* the variable on which the condition is based must have a value prior to the original test • Since we retest the condition after each iteration of the loop body the condition variable must be reassigned a value prior to retesting or we will have an infinite loop • While loop is sometimes called a zero loop because if the condition tests false the first time the body of the loop is never executed (or executed zero times) Initialize condition variableCS 110 Notes – Repetition 4 Copyright C. Tanner 2010 while (condition) { Loop body Update condition variable } • Counted loop example count =0; while (count < 5) { System.out.println(count); count++; } System.out.print (“enter the number of employees: “); numEmployees = sc.nextInt(); countEmp=0; while (countEmp <numEmployees) { //get gross pay //calculate net pay //display gross and net pay rates countEmp++; } • Events o State occurs boolean variable while (state has not been reached) o Sentinel Data value used in input stream to indicate end of data Value used as the sentinel can not be a legitimate value in the input while (inputValue != sentinel value) not all applications can use a sentinel • entering temperatures o what value is not possible? • When no sentinel can be used we base the loop on user input to do more o Example – go on number of employees but we don’t know the number System.out.print(“Enter an Employee: Y/N: “);CS 110 Notes – Repetition 5 Copyright C. Tanner 2010 more = sc.next().charAt(0); while (more ==’y’ || more ==’Y’) { //get gross pay //calculate net pay //display gross and net pay System.out.print(“Enter an Employee: Y/N: “); more = sc.next().charAt(0); } • Example of sentinel loop value = sc.nextInt(); while (value != sentinel) { Process data value = sc.nextInt(); } • Sample programs: Circle2a.java, Minmax2.java, Stats.java • Do loops o Another loop which is based on a condition o Form do { stmts } while (condition) Execute the body Test the condition If true execute the body If false exit the loop • Called a one loop because the statement body is always execute at least one time • Example – display the digits of an integer and sum the digits sum = 0;CS 110 Notes – Repetition 6 Copyright C. Tanner 2010 do { digit = num % 10; sum += digit; num /= 10; }while (num > 0); Why use the do instead of while in this instance?
View Full Document