Loop with Range 0..n
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
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
0+1+2+3 = 6
0+1+2 = 3... wait 0+1+2 = 3, but we need sum...
0+1+2+3+4 = 10
0+1 = 1
0 = 0
Algorithm Flow

Solution Approach
Best Answers
fn solution(n: i32) -> i32 {
let mut sum = 0;
for i in 0..n {
sum += i;
}
sum
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
