call(back)
Algorithms & Data StructureseasySign in to star problems

Sum 1 to n Recursively

Write sumTo(n): the sum n + (n - 1) + ... + 1, computed recursively. n <= 0 gives 0.

sumTo(100)   // 5050
sumTo(0)     // 0
sumTo(-5)    // 0

Hints

Hint 1

The base case is n <= 0, returning 0; otherwise return n + sumTo(n - 1).

Asked at