oneby7

Foundations Recursion basics

38. Sum of the First N Numbers

Easy

Given a whole number n, return the sum of the first n positive whole numbers:

1 + 2 + 3 + … + n

When n is 0 there are no numbers to add, and the sum is 0.

Example 1

Input: n = 6

Output: 21

Explanation: 1 + 2 + 3 + 4 + 5 + 6 = 21.

Example 2

Input: n = 0

Output: 0

Explanation: There are no numbers to add, so the sum is 0.

Example 3

Input: n = 1000

Output: 500500

Check your understanding

Work out the answer for this input before you write any code.

n = 7

Constraints

  • 0 ≤ n ≤ 1000

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.