หลักการโปรแกรม 1 Lecture 9: การทำซ้ำ (for)
ทบทวนเรื่อง while
ทบทวนเรื่อง do-while
The for Statement Syntax for (ForInit ; ForExpression; PostExpression) Action Example for ( int i = 0; i < 3; i++ ) { cout << “i is " << i << endl; }
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 0
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 0
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i 0
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i 0
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i 1
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 1
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i is 1 i 1
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i is 1 i 1
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i is 1 i 2
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i is 1 i 2
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i is 1 i is 2 i 2
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i is 1 i is 2 i 2
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i is 1 i is 2 i 3
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i is 1 i is 2 i 3
Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i is 0 i is 1 i is 2 all done i 3
Example: หาผลรวมของเลข 1 ถึง 10 T F i=i+1 i<=10 sum = sum+i i = 1 sum = 0 sum = 0; for (int i=1; i <= 10; i++ ) sum += i; RESULT: sum =
Example: พิมพ์เลขคี่ที่อยู่ในช่วง 1 ถึง 10 T F i+=2 i < 10 i = 1 print i for (int i=1; i<10; i+=2) cout << i << “ ”; RESULT:
Example: พิมพ์ค่า 10 ลงมาจนถึง 1 i = 10 print i i=i-1 T F i>=1 for (int i=10; i >= 1; i--) cout << i << “ ”;
initialization condition statements update for (int count = 1; count <= 10; count++) { cout << count << endl; } int count = 1; // Initialize the counter while (count <= 10) // Check the counter { cout << count << endl; count++; // Update the counter } initialization condition statements update while vs. for
แบบฝึกหัด ให้เขียนโปรแกรมเพื่อแสดงค่า x 2 + x – 4 เมื่อ x=5, 6, …,12 ให้เขียนโปรแกรมเพื่อแสดงสูตรคูณแม่ 5