# rec5 - CS 177 Week 5 Recitation Slides Loops 1...

This preview shows pages 1–9. Sign up to view the full content.

1 CS 177 Week 5 Recitation Slides Loops

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams posted
3 QUESTIONS???

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
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).

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
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?

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
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?
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 27

rec5 - CS 177 Week 5 Recitation Slides Loops 1...

This preview shows document pages 1 - 9. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online