ภาพรวมปัญหา
ได้รับตัวเลข n ต้องพิมพ์รูปแบบตัวเลขลดลงทีละ 5 จนถึง 0 หรือติดลบ แล้วเพิ่มขึ้นกลับมาที่ n เดิม โดยไม่ใช้ลูป
ตัวอย่าง
Input: n = 12 Output: 12 7 2 -3 2 7 12
วิธีแก้ปัญหา (Recursion)
ใช้ Recursion เรียกฟังก์ชันซ้ำหลังอัปเดตค่า ใช้ตัวแปร flag บอกว่ากำลังลดหรือเพิ่ม
ตัวอย่างโค้ด C++
#include <iostream>
using namespace std;
void printNextValue(int m) {
if (m > 0) {
cout << m << '\t';
printNextValue(m - 5);
}
cout << m << '\t';
}
int main() {
int n = 13;
cout << "The pattern is:\n";
printNextValue(n);
return 0;
}
ผลลัพธ์ (Output)
The pattern is: 13 8 3 -2 3 8 13