day10_FactorialTestEx07

육희영·2021년 10월 26일
0

재귀호출, 삼항연산자

package com.java1.day10;

//재귀호출
public class FactorialTestEx07 {

	public static void main(String[] args) {
		System.out.println(factorial(4));

	}

	static long factorial(int n) {
		long result = 0;
		if (n == 1) {
			result = 1;
		} else {
			result = n * factorial(n - 1); // 다시 메서드 자신을 호출한다.
			// 4 * 3 * 2 * 1 =24;
		}
		return result;
	}
	/*
	 * 삼항 연산자를 사용하면 더 간단합니다. 
	 * static long factorial(int n) {
	 *  return (n == 1) ? 1 : n * factorial(n-1); 
	 *  }
	 */

}

결과출력

24

0개의 댓글

관련 채용 정보