{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# 05 - 03:02:55 CS 61B Lecture 5 Friday Todays reading LOOPS...

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

01/30/09 03:02:55 1 05 CS 61B: Lecture 5 Friday, January 30, 2009 Today’s reading: Sierra & Bates pp. 59-62, 83, 114-116, 293-300, 670. 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.

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}