Language syntax

Java bounded recursion

A recursive call needs a terminating path for every accepted input. Keep depth within documented bounds.

Formal Syntax & Structure

java syntaxjava
if (n == 0) { return 0; } return n + sumTo(n - 1);

Working Example

Example Snippetjava
public class Main {    static int sumTo(int n) {        if (n == 0) { return 0; }        return n + sumTo(n - 1);    }    public static void main(String[] args) {        System.out.println(sumTo(3));        System.out.println(sumTo(0));    }}
Java Reference