Table of Contents

Recursion

기초

예시

#include <studio.h>

void Recursion(int num) {

	//탈출 조건
	if(num <= 0)
		return;

	//탈출 조건을 만들기 위한 인자(Argument)와 재귀 호출
	Recursion(num-1);

	printf("%2d번째 재귀 호출!\n", num);
}

void main() {
	Recursion(3);
}

해설

결론

예제

	public static int sum(int n) {
		if(n <= 0)
			return n;
		
		return n + sum(n - 1);
	}

Factorial

	private static int factorial(int n) {
		if(n == 0) //0! = 1
			return 1;
		else
			return n * factorial(n-1);
	}

Fibonacci Array

	public static int fibonacci(int n) {
		if(n < 1)
			throw new StackOverflowError("1보다 커야 합니다.");
		
		if(n == 1) {
			return 0;
		}
		else if (n == 2) {
			return 1;
		}
		else {
			return fibonacci(n - 1) + fibonacci(n - 2);
		}
	}

Hanoi Tower

	public static void hanoiTower(int n, String from, String to, String temp) {
		if(n == 1) {
			System.out.println(String.format("원반 %d개 %s → %s", n, from, temp));
		}
		else {
			hanoiTower(n - 1, from, temp, to);
			System.out.println(String.format("원반 %d개 %s → %s", n, from, temp));
			
			hanoiTower(n - 1, temp, from, to);
		}
	}