05 - 19:40:22 CS 61B Lecture 5 Wednesday September 8 2010 Todays reading 1 05 Sierra Bates pp 59-62 83 114-116 293-300 670 LOOPS ="while

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
09/08/10 19:40:22 1 05 CS 61B: Lecture 5 Wednesday, September 8, 2010 Today’s reading: LOOPS ===== "while" Loops ------------- A "while" statement is like an "if" statement, but the body of the statement is executed repeatedly, as long as the condition remains true. The following example tests whether n is a prime number by attempting to divide it by every integer in the range 2. ..n - 1. public static boolean isPrime(int n) { int divisor = 2; while (divisor < n) { _ <- "divisor < n" is the _loop_condition_. if (n % divisor == 0) { | return false; | These lines inside the braces } | are called the _loop_body_. divisor++; _| } return true; } Here’s how the loop executes. - When Java reaches this "while" loop, it tests whether the loop condition "divisor < n" is true. - If divisor < n, Java executes the loop body {in braces}. - When Java finishes the loop body (i.e. after executing "divisor++"), it tests _again_ whether "divisor < n" is true. - If it’s still true, Java jumps back up to the beginning of the loop body and executes it again. - If Java tests the loop condition and finds that "divisor < n" is false, Java continues execution from the next line of code _after_ the loop body. An _iteration_ is a pass through the loop body. In this example, if n is 2 or less, the loop body won’t iterate even once. "for" Loops ----------- "for" loops are a convenient shorthand that can be used to write some "while" loops in a more compact way. The following "for" loop is equivalent to the following "while" loop. for (initialize; condition; next) { | initialize; statements; | while (condition) { } | statements; | next; | } By convention, the "initialize" and "next" are both expressions that affect a variable that changes every loop iteration and is central to the test. Most
Background image of page 1

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

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/10/2012 for the course CS 61B taught by Professor Canny during the Fall '01 term at University of California, Berkeley.

Page1 / 2

05 - 19:40:22 CS 61B Lecture 5 Wednesday September 8 2010 Todays reading 1 05 Sierra Bates pp 59-62 83 114-116 293-300 670 LOOPS ="while

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online