flow of control recitation – 09/(18,19)/2008 cs 180 department of computer science, purdue...
Post on 21-Dec-2015
219 views
TRANSCRIPT
Flow of Control Recitation – 09/(18,19)/2008
CS 180
Department of Computer Science,
Purdue University
• Now posted on the class webpage.
• Due Wed, Sept. 24 at 10 pm.
• Start early. All questions on the class newsgroup.
• Exam in 2 weeks (10/1); Consult Mentor (Debbie) for more on pattern, advice etc.
• Evening consulting hours.
LWSN B146. MTW 7-10 pm.
Project 3 and Exam
• Loop statements
• while
• do-while
• for
• break and continue statements
• Display text in Applets
Outline
• A portion of a program that repeats a statement or a group of statements is called a loop
• The statement or group of statements to be repeated is called body of the loop
• A loop could be used to compute sum of N numbers
What are Loops?
• while loop continuously executes a block of statement until a particular condition is true
• Syntaxwhile (boolean_expression){
statement;}
The while statement
• Example:
int count = 1;while (count < 11)
{ System.out.println ("Count is: " +
count); count++;
}
while statement example
The do-while statement• Similar to a while statement, except that the loop
body is executed at least once
• Syntaxdo{
Statement;} while (Boolean_Expression);
• Remember the semicolon at the end of while. It helps the compiler to distinguish do-while and while statements
• Example:
int count = 1;do
{ System.out.println ("Count is: " +
count); count = count+1;
} while (count<=10);
do-while statement example
• Syntax for (Initialization; Condition;
Update){
statement;}
• Initialization expression initializes the loop and is executed once at the beginning
• Loop terminates when the Condition evaluates to false
• Update can be an increment or a decrement on a variable. It is executed after the first iteration
The for statement
• Example: Print all even numbers in the first 10 numbers
for (int count =1; count<=10;count++) {
if(count%2 == 0) System.out.print(count+” ”); }
Output: 2 4 6 8 10
for statement example 2
• Useful to operate on collection of data such as enumeration
• Example
enum Names {James, Joshua, Scott}
for (Names name: Names.values())
System.out.println(name+” ”);
• Names.values() represent all the values in the enumeration.
The for-each statement
The break statement• break statement can be used to end the loop
immediately• Example:
for (int n=1; n<=5;n++){
if (n==3){
break;}System.out.print(n+” ”);
}
• Output: 1 2
The continue statement• A continue statement ends current loop iteration
and begins next iteration• Example:
for (int i = 0; i < 10; i++){ if (i == 5) { continue; } System.out.print(i+” ”); }
• Output: 0 1 2 3 4 6 7 8 9• It is recommended to sparingly use break and
continue statements
loops in Applets
• A multiface Applet• Uses loop to draw several smiley faces• Uses if statement to alter appearance
• View sample program, listing 4.9class MultipleFaces