void func(int x) {
if (멈추는 조건) return; // ✅ 종료 조건 (기저 조건)
func(x - 1); // 🔁 자기 자신을 다시 호출
}
✔ 언제까지 반복하나?
👉 종료 조건이 참이 될 때까지 계속 호출됩니다.
✔ 왜 무한 반복이 안 되나?
👉 매번 값이 바뀌면서 종료 조건에 가까워지기 때문이에요.
#include <iostream>
using namespace std;
void print(int n) {
if (n == 0) return; // ⛔ 멈추는 조건
cout << n << "\n"; // 🔽 출력
print(n - 1); // 🔁 자기 자신 호출
}
int main() {
print(3);
}
▶ print(3) 호출
print(3)
├─ n == 0 ? ❌
├─ 출력: 3
└─ print(2) 호출
print(2)
├─ n == 0 ? ❌
├─ 출력: 2
└─ print(1) 호출
print(1)
├─ n == 0 ? ❌
├─ 출력: 1
└─ print(0) 호출
print(0)
├─ n == 0 ? ✅
└─ return (끝)
print(3)
└─ print(2)
└─ print(1)
└─ print(0) ← 종료 조건 도착
출력이 먼저 (위에서 출력)
cout << n << "\n";
print(n - 1);
3
2
1
출력이 나중 (아래에서 출력)
print(n - 1);
cout << n << "\n";
1
2
3
To embed this project on your website, copy the following code and paste it into your website's HTML: