Control Statement แบบทำซ้ำ for
การทำงานของ for จะตามลำดับดังนี้
- initialization คือ การกำหนดค่าเริ่มต้นให้ตัวแปร ตัวแปรนี้ส่วนใหญ่จะถูกนำไปใช้ในเงื่อนไขการทำซ้ำ
- loopContinuationCondition คือ ส่วนเงื่อนไขของการทำซ้ำเมื่อเป็นจริง (true) จะทำต่อไป ถ้าเป็นเท็จ (false) จะหยุดทำ
- statement คือ ส่วนคำสั่งที่ต้องการทำซ้ำ
- increment คือ ส่วนการเพิ่มค่าตัวแปร ส่วนนี้มักนำตัวแปรจากส่วน initialzation มาเพิ่มค่า
for (initialization; loopContinuationCondition; increment)
statement
ตัวอย่างลำดับการทำงานของ for
รอบที่ 1
- initialization
- loopContinuationCondition เมื่อเงื่อนไขเป็นจริง (true)
- statement
- increment
รอบที่ 2
- loopContinuationCondition เมื่อเงื่อนไขเป็นจริง (true)
- statement
- increment
รอบที่ 3
- loopContinuationCondition เมื่อเงื่อนไขเป็นเท็จ (false)
- ออกจากการทำซ้ำ
แสดงลักษณะเป็น Flow chart ดังตัวอย่างด้านล่าง
ตัวอย่างโปรแกรมการแสดงค่า 1 - 10 ด้วยการใช้ while loop
Source Code
public class For {
public static void main(String[] args) {
for (int count = 1; count <= 10; count++) {
System.out.println("%d ", count);
}
System.out.println();
}
}
Output
1 2 3 4 5 6 7 8 9 10
Control Statement แบบ for เป็นที่นิยมมากสำหรับผู้เริ่มต้นเขียนโปรแกรม เนื่องจากเข้าใจได้ง่ายกว่าแบบอื่นๆ ผู้เขียนเลยจะยกตัวอย่างการเขียน for แบบแปลกๆ "ท่ายาก" ที่ผู้อ่านอาจจะยังไม่เคยเห็น
แบบที่ 1 เลียนแบบ while ด้วยการใช้ for
int count = 1;
for (;;) {
System.out.printf("%d ", count);
if (count == 10) {
break;
}
count++;
}
แบบที่ 2 เพิ่มตัวแปรในส่วน initialization, increment
for (int i =1, j = 20; i <=10 ; i++, j+=2) {
System.out.printf("%d ", j);
}
System.out.println();
แบบที่ 3 ใน for สามารถใส่เพียงบ้างส่วนได้
int count = 1;
for(;;count++) {
System.out.printf("%d ", count);
if (count == 10) {
break;
}
}
System.out.println();
บทความถัดไป
สอน Java ตอนที่ 7.4 การใช้คำสั่ง break และ continue