 # 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.

## Presentation on theme: "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."— Presentation transcript:

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 posted

3 QUESTIONS???

While Loops Uses repetition to perform a lot of work very fast They look a lot like if statements: 4 int x = 0; if(x < 5) { /*do work using statements*/ } int x = 0; while(x < 5) { /*do work using statements*/ } When here, finished When here, loop back up And test again… x += 1; Need to assure a statement is in place to cause the expression to eventually evaluate to false

While Braces are optional for a single statement while (i < 10) sum += i++; As with ifs, only when the expression is true will the statements within the while block be executed. The big difference is that when the last statement of a while is executed (if the expression was first true), the expression will be re-evaluated. 5  MUST BE CAREFUL that the condition will depend on a value that changes as the loop progresses or a “break” will be needed (to be discussed).

Small contrived example boolean value = true; //program statements… while (value) { System.out.println(“If here, value is true!”); value = false; System.out.println(“value can change…”) System.out.println(“But ONLY matters at the end”); value = true; } 6 With value set to true in the end it will loop forever

boolean value = true; //program statements… int count = 0; while (value) { System.out.println(“If here, value is true!”); value = false; //… lots of work value = true; count++; } 7 if (count > 10) value = false; This causes the loop to stop… After how many iterations??? i.e. how many times will If here, value is true! print?

Keep multiplying input numbers until a sentinel reached 8 int i = 1; int product = 1; while( i != 0 ) { product *= i; System.out.print(“Enter number: “); i = StdIn.readInt(); } System.out.println(“Product: “ + product); What is the sentinel here? Why is i initialized to 1? So that the while expression will evaluate to true to first enter the loop but also once inside the loop, multiplying by 1 does not affect the final value (as opposed to i = 2).

From lecture: 9 int i = 0; double sum = 0; int count = 0; while( i >= 0 ) { sum += i; count++; System.out.print(“Enter number: “); i = StdIn.readInt(); } count--; //fixes extra count for sentinel System.out.println(“Average: “ + (sum/count)); Getting the sentinel value counted as1 input, so, just calculate with (count-1) to calculate with just the actual values +(sum/(count-1)));

Infinite Loops  int i = 0; int sum = 0; while(i <= 10) { sum += i; } 10 This loop will run forever! WHY??? How do we fix this? i++; This run-time error is a little harder to make when using for loops…

for loops for(init; condition; inc) { //statements } 11 init; //statement while(condition) { //statements inc; //statement } Without increment statements, loops can run forever (unless there is a break… to-be-discussed) but with for loops, you add it right at the beginning.

Side by Side 12 int i = 0; int sum = 0; while(i <= 10) { sum += i; i++; } int sum = 0; for(int i = 0; i <= 10; i++) { sum += i; }

for loops cont. 13 int sum = 0; for(int i = 0; i <= 10; i++) { sum += i; } init performed once only at beginning of loop. condition is checked at the beginning and before each next loop iteration inc is performed at the end of every loop iteration just before condition is rechecked

Another Painful Error for Both while and for Loops int i = 0; int sum = 0; while(i <= 10); { sum += i; i++; } 14 int sum = 0; for(int i = 0; i <= 10; i++); { sum += i; } Semicolons placed here will give you a not-so-expected result!! What will happen in the two cases and why??? Will be different for each. For loop will have a compilation error since i is declared inside the loop and i is used “outside” of loop…

What about 15 int sum = 0; int i; for(i = 0; i <= 10; i++); { sum += i; } What will sum and i be here (no error this time…)?

When do we use whiles and when do we use fors? The answer is not EXACTLY clear cut, BUT there is a general use for each that seems natural: 16  for loops are great for “count controlled” loops; i.e. loops that have a count with them. Loops from 1 to 100 for instance  while loops are great for “event controlled” loops; i.e. loops that keep iterating until some event has occurred Loop until program gets correct input for instance

From lecture… The following code will tell you if a number isn’t prime What’s the problem? 17 int number = StdIn.readInt(); for( int i = 2; i < number; i++) { if( number % i == 0 ) { System.out.println(number + “ is not prime.”); }

cont. By adding a boolean, we can keep track of whether or not the number is prime 18 int number = StdIn.readInt(); boolean prime = true; for( int i = 2; i < number && prime; i++) { if( number % i == 0 ) prime = false; } 18 break; Some might think this would work? (and in a way it does…) BUT What about when the loop is finished and we want to know LATER if the number is actually prime without doing the loop again?? ; i++)

do-while Work just like while loops, only execute statements once before ever checking the condition… do { //statements… } while(condition); 19 Note here the semicolon, because it is at the end NOT at the beginning, it denotes the end of the statement.

Get a password/combination String combinationForDruidea; //anyone name the movie? do { System.out.println(“Please enter password:”); combinationForDruidea = StdIn.readString(); } while( !(combinationForDruidea.equals(“1234”) ); //”Amazing, now I’m going to have to change the //combination on my luggage!” 20 If you know the loop will have to execute the statements AT LEAST once, then you can use a do-while loop.

Side by Side for product int product = 1; System.out.print(prompt); int x = StdIn.getInt() while(x != 0) { product *= x; System.out.print(prompt); x = StdIn.getInt(); } 21 int product = 1; int x; do { System.out.print(prompt); x = StdIn.getInt(); product *= x; } while(x != 0) String prompt = “Please enter a number to multiply to the product Enter 0 to quit\n”);

import lejos.nxt.*; public class BasicRobotTest { public static void main(String[] args) { TouchSensor tSensor = new TouchSensor(SensorPort.S1); int x = 3; LCD.drawInt(x, 0, 0); Sound.beep(); pause(1000); LCD.drawString("Touch me to", 0, 0); LCD.drawString("shut me up!", 0, 1); while (!tSensor.isPressed()) { Sound.buzz(); } Motor.A.setSpeed(720); Motor.C.setSpeed(720); Motor.A.forward(); Motor.C.forward(); pause(1000); Motor.A.stop(); Motor.C.stop(); } 22 int x = 3; LCD.drawInt(x, 0, 0); Sound.beep(); pause(1000); LCD.drawString("Touch me to", 0, 0); LCD.drawString("shut me up!", 0, 1); while (!tSensor.isPressed()) { Sound.buzz(); } Motor.A.setSpeed(720); Motor.C.setSpeed(720); Motor.A.forward(); Motor.C.forward(); pause(1000); Motor.A.stop(); Motor.C.stop(); Displays a 3 and beeps for a second Displays “Touch me to shut me up!” Loop to buzz forever UNTIL the sensor is pressed Sets the speed of the motors Tells the motors to move forward at that speed for a second then to stop. Next week’s Lego Lab Starter

Last Bit on Loop Errors BE CAREFUL!!  When using loops, you have to follow the syntax and the logic you want EXACTLY or a lot can go wrong. 23 If you have a loop and the program just seems to sit there, you may have an infinite loop.  Infinite Loops can be caused for various reasons… In cases, your value can be off by 1 if you’re not careful. Sometimes, a condition can look right but is actually wrong, a loop may never execute… And the misplaced semicolon can make life miserable!

Infinite Loops int x = 0; do { System.out.println(x); }while(x < 10) 24 for(int x = 0; x < 10; x++) { System.out.println(x); /*code that make you feel you’ve accomplished something */ x--; //even more code } How would we fix either? What about? x--

Off by 1 int ranThrough = 0; for(int i = 1; i < 40; i++) { System.out.println(i); ranThrough++; } System.out.println(“The loop ran through “ + ranThrough + “ times”); 25 What will print here? What will be the printed value of i on the LAST print statement? ranThrough is 39!

Problems? for(int i = 1; i >= 40; i++) System.out.println(i); 26 This will never print anything…. WHY? Looks right but a logic problem with expression… int i; for(i = 1; i <= 40; i++); System.out.println(i); What is the problem? What will actually print and how many times? for(int i = 1; i <= 40; i++); System.out.println(i); //gives compilation error! //i used “outside” loop //where it was declared.

27 Final QUESTIONS???

Download ppt "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."

Similar presentations