Java class 2010.10.22. Outline for loop while loop do while loop How to choose? Nested loop.

13
Java class 2010.10.22
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    239
  • download

    3

Transcript of Java class 2010.10.22. Outline for loop while loop do while loop How to choose? Nested loop.

Java class2010.10.22

Outline

• for loop

• while loop

• do while loop

• How to choose?

• Nested loop

for loop

EX:

for ( i=0 ; i<=100 ; i++ ) // 迴圈條件運算式{

// 迴圈內的動作 ;

}

迴圈內的動作迴圈內的動作

進入迴圈

true

false

離開迴圈

迴圈條件運算式

while loop EX:

int count=0;

while ( count<100 )

{

System.out.println(”Hello!”);

count++;

}

p.s count 從 0 累加到 99

loop-

continuation condition?

Statement(s)(loop body)

false

true

count=0

(count < 100) ?

System.out.println(“Hello!”);count++;

練習 :

用 for loop 以及 while loop, 寫九九乘法表 格式 :

do while loop

EX:

int count=0;

do {

System.out.println(”Hello!”);

count++;

} while ( count<100 );

loop-continuation condition?

Statement(s)(loop body)

false

true

count=0

(count < 100) ?

System.out.println(“Hello!”);count++;

Pretest & Posttest loop

• 先測迴圈 : while 、 for

The condition is checked before the loop body is excuted.

• 後測迴圈 : do while

The condition is checked after the loop body is excuted.

How to choose?

A for loop may be used if the number of repetitions is known in advance.

A while loop may be used if the number of repetitions is not fixed.

A do while loop can be used to replace a while loop if the loop body has to be executed before the condition is tested.

課本 p.152

Nested( 巢狀 ) loop

for

{

…….

for

{

…….

}

}

課本 p.153

回家看 :

p.152 ~ p.153