본문 바로가기

CodingTest Practice

[인프런] 재귀함수

재귀함수

자연수 N이 입력되면 재귀함수를 이용하여 1부터 N까지 출력하는 프로그램을 작성

 

■ 문제 풀이

1) 입력 설명
- 첫 번째 줄은 정수 N(3<=N<=10)이 입력된다

2) 출력 설명
- 첫째 줄에 출력한다.

3) 테스트
- input : 3
- output : 1 2 3

4) 재귀함수 호출 그림으로 표현

 

import java.util.Scanner;

public class Main {

    private void recursive(int input) {
        if (input == 0) {
            return;
        }else {
            recursive(input -1);
            System.out.print(input + " ");
        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        Scanner scanner = new Scanner(System.in);
        int input = scanner.nextInt();

        main.recursive(input);
    }
}

 

'CodingTest Practice' 카테고리의 다른 글

[인프런] 학급 회장  (0) 2022.04.26
[인프런] 이진수 출력  (0) 2022.04.22
[인프런] 뒤집은 소수  (0) 2022.04.21
[인프런] 소수 구하기(에라토스테네스의 체)  (0) 2022.04.15
[인프런] 가위 바위 보  (0) 2022.04.14