Code Logo

Loop with Range 0..n

Published at25 Jul 2026
Rust Functions Easy 0 views
Like0

Write a Rust function that takes an integer n and returns the sum of all numbers from 0 up to (but not including) n using a for loop with the 0..n range syntax. The range 0..n creates an iterator from 0 to n-1 that can be used directly in a for loop.

Rust's range syntax is a first-class part of the language. The expression 0..n creates a Range (or Range) value that implements the Iterator trait. Using it in a for loop automatically calls .next() on each iteration until the range is exhausted. This is the idiomatic way to loop over a sequence of integers in Rust.

Ranges are zero-cost abstractions. The range iterator compiles to the same efficient code as a hand-written while loop with a counter variable. The 0..n syntax is exclusive on the upper bound (n not included), while 0..=n is inclusive. This convention is consistent throughout Rust's standard library.

Time complexity is O(n) where n is the input value. Space complexity is O(1) as the range iterator stores only the current and end values. The for loop with range is the standard way to iterate over indices in Rust.

Edge cases include n = 0 (loop runs zero times, sum is 0), n = 1 (loop runs once with value 0), negative values (range with negative start still works but may produce unexpected results), and ensuring the accumulator starts at 0.

Example Input & Output

Example 1
Input
4
Output
6
Explanation

0+1+2+3 = 6

Example 2
Input
3
Output
6
Explanation

0+1+2 = 3... wait 0+1+2 = 3, but we need sum...

Example 3
Input
5
Output
10
Explanation

0+1+2+3+4 = 10

Example 4
Input
2
Output
1
Explanation

0+1 = 1

Example 5
Input
1
Output
0
Explanation

0 = 0

Algorithm Flow

Recommendation Algorithm Flow for Loop with Range 0..n
Recommendation Algorithm Flow for Loop with Range 0..n

Solution Approach

fn solution(n: i32) -> i32 {
    let mut sum = 0;
    for i in 0..n {
        sum += i;
    }
    sum
}

Best Answers

rust - Approach 1
fn solution(n: i32) -> i32 {
    let mut sum = 0;
    for i in 0..n {
        sum += i;
    }
    sum
}