Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Java Programming Lecture 8 Flow Control : while do-while and for loops.

Similar presentations


Presentation on theme: "Introduction to Java Programming Lecture 8 Flow Control : while do-while and for loops."— Presentation transcript:

1

2 Introduction to Java Programming Lecture 8 Flow Control : while do-while and for loops

3 While loop Example : int i = 0; while (i < 100) { System.out.println("Welcome to Java!"); i++; } Syntax ( 語法 ) : while (boolean_expression) { // statement_list; } 1. Initialization 初始值 4. Update: In this case, you can use either the pre or post increment operator. 變數值的改 變 2. Test Condition 判斷條件式 3. Loop body 迴圈主敘述

4 Do - while loop Syntax ( 語法 ) : do { // statement_list 至少執行一次 ; } while ( boolean_expression ); int i = 0; do { System.out.println("Welcome to Java!"); i++; } while (i<100); 1. Initialization 4. Test Condition 3. Update: In this case, you can use either the pre or post increment operator. 2. Loop body

5 Comparing while and do-while int i = 0; while (i < 100) { System.out.println("Welcome to Java!"); i++; } int i = 0; do { System.out.println("Welcome to Java!"); i++; } while (i<100);

6 Basic For Loop Example : ( 我們較常使用 for 來寫固定次數的迴圈 ) int counter; for (counter =1; counter <= 100; counter++) System.out.println ("Welcome to Java! ” + counter); 1. initialization 2. Test Condition 4. Update: Update the value. Note that each section is separated by a semicolon. Syntax ( 語法 ) : for(initialization; test condition; update expression){ //loop body; } 3. Loop body

7 Comparing While and for loops 可用 while 寫的迴圈,用 for 也寫得出來,反之亦然 int i = 0; while (i < 100) { System.out.println("Welcome to Java! ” + i); i++; } int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Java! ” + i); }


Download ppt "Introduction to Java Programming Lecture 8 Flow Control : while do-while and for loops."

Similar presentations


Ads by Google