easyBasic Recursion

Print 1 to N using Recursion

Print the integers from 1 to n using recursion instead of a loop.

Work through the cases

3 examples

Input notation

An integer n from 1 through 100.

Expected result

The integers separated by spaces.
Case 1

Input

4

Expected output

1 2 3 4
Case 2

Input

1

Expected output

1
Case 3

Input

2

Expected output

1 2

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

Recursively print the smaller prefix before the current number. Time and call-stack space: O(n).

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        ArrayList<Long> values = new ArrayList<>();
        while (in.hasNextLong()) values.add(in.nextLong());
        long[] a = values.stream().mapToLong(Long::longValue).toArray();
        long n = a[0];
        class R { void f(long k){if(k==0)return;f(k-1);System.out.print(k+" ");} } new R().f(n);
    }
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.