มีหลายวิธีพิมพ์ตัวเลข 1-100 โดยไม่ใช้ Loop (for/while/do-while) ใช้ Recursion, Goto, หรือ Function Calls
วิธีที่ 1: Recursion (ฟังก์ชันเรียกตัวเอง)
#include <stdio.h>
void printNumbers(int n) {
if (n <= 100) {
printf("%d ", n);
printNumbers(n + 1); // Recursive Call
}
}
int main() {
printNumbers(1);
return 0;
}
วิธีที่ 2: Goto Statement
#include <stdio.h>
int main() {
int i = 1;
PRINT:
printf("%d ", i);
i++;
if (i <= 100) goto PRINT;
return 0;
}
วิธีที่ 3: Function Pointer Array / Table
#include <stdio.h>
void print1() { printf("1 "); }
void print2() { printf("2 "); }
// ... เขียน 100 ฟังก์ชัน (ไม่เป็นประโยชน์)
void (*funcs[100])() = {print1, print2, ... };
int main() {
for (int i = 0; i < 100; i++) funcs[i](); // ยังใช้ Loop
return 0;
}
วิธีที่ 4: Template Metaprogramming (C++ เท่านั้น - Compile Time)
#include <iostream>
template <int N>
struct Print {
static void run() {
Print<N-1>::run();
std::cout << N << " ";
}
};
template <>
struct Print<1> {
static void run() { std::cout << "1 "; }
};
int main() {
Print<100>::run(); // Compile-time Recursion
return 0;
}
วิธีที่ 5: std::iota + Algorithm (C++ Modern)
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <iterator>
int main() {
std::vector<int> v(100);
std::iota(v.begin(), v.end(), 1); // Fill 1..100
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
วิธีที่ 6: Recursive Lambda (C++14+)
#include <iostream>
#include <functional>
int main() {
std::function<void(int)> print = [&](int n) {
if (n <= 100) {
std::cout << n << " ";
print(n + 1);
}
};
print(1);
return 0;
}
ผลลัพธ์ (ทุกวิธี)
1 2 3 4 5 6 7 8 9 10 11 12 ... 98 99 100
การเปรียบเทียบ
| วิธี | ภาษา | Stack Usage | Compile Time | Practical |
|---|---|---|---|---|
| Recursion | C/C++ | O(n) Stack Frames | Fast | ✗ Stack Overflow Risk |
| Goto | C/C++ | O(1) | Fast | ✗ Bad Practice |
| Template Metaprogramming | C++ Only | O(1) Runtime | Slow (Template Depth) | ✓ Compile-time |
| std::iota + Algorithm | C++ | O(1) | Fast | ✓ Best Practice |
| Recursive Lambda | C++14+ | O(n) | Fast | △ เพื่อความสนุก |
ข้อสังเกต
- Recursion Depth: 100 ระดับ ปกติ Stack รับได้ (Default Stack ~8MB) แต่ไม่ควรทำกับค่ามาก
- Tail Recursion: Compiler อาจ Optimize เป็น Loop (Tail Call Optimization)
- Production Code: ใช้ Loop ปกติหรือ STL Algorithms - อ่านง่าย เร็ว ปลอดภัย
สรุป
หลายวิธีทำได้แต่ Recursion และ Goto เป็นคำตอบมาตรฐานสำหรับคำถามสัมภาษณ์ ในงานจริงใช้ Loop หรือ STL Algorithms