Recursion Function

Factorial 같은 함수를 구현하기 위해서는, 자기자신의 출력값을 다시 불러야 되는 필요성이 있다. 이것을 재귀함수라 한다.

Example

#include <iostream>
using namespace std;
 
int factorial(int n);
 
int main(){
    cout << factorial(0) << endl;
    cout << factorial(1) << endl;
    cout << factorial(6) << endl;
    cout << factorial(10) << endl;
    
    return 0;
}
 
int factorial(int n){
    if (n == 0)							// 제약조건
        return 1;
    else
        return n * factorial(n-1);
}

이 과정을 알아보면,

6일 때, n-1 factorial 을 불러야 하므로 5 factorial 로 간다. 같은 방법으로 제약조건인 n==1 일 때까지 갔다가, 도착하면 순차적으로 값을 얻어와 최종 값을 반환한다.

Reference