ลูป: for, while และ do-while
ลูปรันบล็อกเดิมหลายครั้ง for เหมาะกับจำนวนรอบที่รู้ล่วงหน้า while ทำซ้ำจนเงื่อนไขเป็นเท็จ และ do-while รันตัวลูปอย่างน้อยหนึ่งครั้งเสมอ
ลูป: for, while และ do-while คืออะไร?
ลูปรันบล็อกเดิมหลายครั้ง for เหมาะกับจำนวนรอบที่รู้ล่วงหน้า while ทำซ้ำจนเงื่อนไขเป็นเท็จ และ do-while รันตัวลูปอย่างน้อยหนึ่งครั้งเสมอ
ทำงานซ้ำด้วยลูป for, while และ do-while พร้อม break และ continue
ประเด็นสำคัญ
- เปิด compiler warning และแก้ทุกคำเตือน
- รู้ type และ lifetime ของทุกค่า
- ตรวจ input และขอบเขต array ให้ชัดเจน
ดูการทำงาน
กด ทีละขั้น เพื่อรันลูปทีละก้าว ดูการตรวจเงื่อนไข การทำงานของตัวลูป และตารางติดตามที่เพิ่มขึ้นทีละแถว
ตัวอย่างโค้ด C และ C++
#include <stdio.h>
int main(void) {
/* for: start; condition; step */
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
/* while: repeat as long as the condition holds */
int n = 20;
int steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
printf("halved %d times\n", steps);
/* do-while: the body runs at least once */
int tries = 0;
do {
tries++;
} while (tries < 3);
printf("tries = %d\n", tries);
/* break leaves the loop, continue skips to the next round */
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
if (i > 7) break;
printf("%d ", i);
}
printf("\n");
return 0;
}
1 2 3 4 5
halved 4 times
tries = 3
1 3 5 7
#include <iostream>
#include <vector>
int main() {
// for: start; condition; step
for (int i = 1; i <= 5; i++) {
std::cout << i << ' ';
}
std::cout << '\n';
// while: repeat as long as the condition holds
int n = 20;
int steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
std::cout << "halved " << steps << " times\n";
// do-while: the body runs at least once
int tries = 0;
do {
tries++;
} while (tries < 3);
std::cout << "tries = " << tries << '\n';
// range-based for visits every element of a container
std::vector<int> values{1, 3, 5, 7};
int sum = 0;
for (int value : values) {
sum += value;
}
std::cout << "sum = " << sum << '\n';
}
1 2 3 4 5
halved 4 times
tries = 3
sum = 16
เปรียบเทียบ C และ C++
ส่วนหัวของ for มีค่าเริ่มต้น เงื่อนไข และการเพิ่มค่า break ออกจากลูปก่อนกำหนด และ continue ข้ามไปรอบถัดไป C++ มี for แบบช่วงที่ไล่ทุกสมาชิกของคอนเทนเนอร์โดยไม่ต้องใช้ดัชนี
C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน
C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เพิ่ม input ผิดและค่าขอบเขต
- Compile ด้วย -Wall -Wextra -Wpedantic
- แยก declaration และ implementation
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- Sum of Odd Numbers Add every odd number up to a limit. ง่าย
- Countdown to Liftoff Count down from a number and end with Liftoff! ง่าย
- Multiplication Table Row List the first multiples of a number. ง่าย