Last Updated: June 7, 2026
Counting from 1 up to a target underlies generating row numbers, filling a range of indices, and producing a sequence to iterate over.
Given a positive integer n, return a list that starts at 1 and ends at n, with every integer in between. If n is 5, the answer is [1, 2, 3, 4, 5]. If n is 1, the answer is just [1].
A plain loop or recursion can do the counting. Both produce the same array.
1 <= n <= 1000 → n is always at least 1, so you never have to return an empty array. The values stay small, so a plain int holds every element without any overflow concern.1 to n from left to right. Whatever method you use, the first value added has to be 1 and the last has to be n.Start a counter at 1, add it to the result, then move the counter up by one and repeat. When the counter passes n, every number has been added and the loop ends.
The detail to get right is the loop boundary. The counter has to reach n itself, so the condition is i <= n rather than i < n. Using i < n would stop one number short and leave n out of the result.
i at 1.i is less than or equal to n, add i to the list and increase i by one.Input:
The loop starts with i = 1 and adds 1 to the list. It then adds 2, 3, and 4 on the next passes. When i reaches 5, the condition i <= 5 is still true, so 5 is added. After that i becomes 6, the condition fails, and the loop stops. The list now holds every number from 1 to 5:
n, doing constant work each time.n integers. No other extra storage is used.The same counting can be expressed through repeated function calls instead of a loop.
Recursion breaks the problem into one number plus a smaller version of the same task. To list the numbers from 1 to n, first list the numbers from 1 to n - 1, then add n at the end. That smaller list follows the same rule, so it lists 1 to n - 2 first and adds n - 1, and so on.
A helper carries the current value down the chain and appends it as it goes, keeping the numbers in increasing order. The base case stops the chain: once the current value passes n, there is nothing left to add, so the recursion returns.
i.i is greater than n, stop, since every number has been added.i to the list, then call the helper with i + 1.1 and return the filled list.Input:
The helper starts at i = 1, adds 1, and calls itself with 2. That call adds 2 and calls itself with 3. The next call adds 3 and calls itself with 4. Since 4 is greater than n, that call stops without adding anything, and the chain unwinds. The numbers were added in the order 1, 2, 3, so the result is in increasing order:
n, doing constant work in each call.n integers, and the chain of recursive calls adds up to n frames on the call stack at its deepest point.