Menu
CoddyTech

Range Guide

Part of the Fundamentals section of Coddy's Rust journey. Lesson 65 of 75.

In this lesson we will explore more about how range works.

Basic Syntax Range:

  • start..end - Creates a range from start to end (exclusive)
  • start..=end - Creates a range from start to end (inclusive)
  • ..end - Creates a range from 0 to end (exclusive)
  • ..=end - Creates a range from 0 to end (inclusive)
  • start.. - Creates a range from start to infinity
  • .. - Creates a range from negative infinity to positive infinity

Reverse Range using .rev():

  • (0..5).rev() - 4, 3, 2, 1, 0
  • (0..=5).rev() - 5, 4, 3, 2, 1, 0

Step Jumps using .step_by(n):

  • (0..10).step_by(2) - 0, 2, 4, 6, 8
  • (0..10).rev().step_by(2) - 9, 7, 5, 3, 1

For example:

// Basic forward range
for i in 0..5 { }
// Values: 0, 1, 2, 3, 4
// Inclusive range
for i in 0..=5 { }
// Values: 0, 1, 2, 3, 4, 5
// Reverse range
for i in (0..5).rev() { }
// Values: 4, 3, 2, 1, 0
// Step by 2
for i in (0..10).step_by(2) { }
// Values: 0, 2, 4, 6, 8
// Combine reverse and step
for i in (0..10).rev().step_by(3) { }
// Values: 9, 6, 3, 0
challenge icon

Challenge

Easy

You are given two arrays, numbers1 and numbers2. Print one line for each:

  • Array 1: start at the last position of numbers1 and move backwards 3 positions at a time (indexes 25, 22, 19, ...), printing the value at each position.
  • Array 2: go through numbers2 from the last element to the first and print only the values divisible by 4.

Print each value in square brackets, with , between values and nothing after the last one:

Array 1: [26], [23], [20], ...
Array 2: [36], [36], ...

Try it yourself

fn main() {
    let numbers1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26];
    let numbers2 = [17, 53, 24, 77, 84, 98, 24, 36, 89, 31, 36];
    print!("Array 1: ");
    // Write your code here
    
    println!();
    print!("Array 2: ");
    // Write your code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Rust compiler