Menu
Coddy logo textTech

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

Create a program that starts with two arrays of numbers and prints the first for the first array all of the numbers in reverse in jumps of 3 through the array positions, and for the second it prints all numbers that are divisible by 4 in reverse order.  Print in the following format:

Array 1: [1], [2], [3], ...
Array 2: [1], [2], [3], ...

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