basics · beginner · ~15 min

Sum a range

Write a small unit a build would compile and link.

Challenge

Sum every integer in an inclusive range.

Task

Implement long sum_range(int lo, int hi) that returns the sum of all integers from lo to hi inclusive. If lo > hi the range is empty, so return 0. No main — the grader calls it.

Input

The inclusive bounds int lo and int hi.

Output

Returns the sum of lo..hi, as a long (0 if lo > hi).

Example

sum_range(1, 5)    ->   15    (1+2+3+4+5)
sum_range(7, 7)    ->   7
sum_range(5, 1)    ->   0     (empty range)
sum_range(-2, 2)   ->   0     (-2-1+0+1+2)

Edge cases

  • lo > hi returns 0.
  • A single-value range (lo == hi) returns that value.

Input format

The inclusive bounds int lo and int hi.

Output format

The sum of lo..hi as a long, or 0 if lo > hi.

Constraints

lo > hi returns 0.

Starter code

long sum_range(int lo, int hi) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.