w3resource

Rust Vector iteration guide

Rust Vectors: Exercise-4 with Solution

Write a Rust program to create a vector with integers 1 to 5. Iterate over the vector and print each element multiplied by 3.

Sample Solution:

Rust Code:

// Define the main function
fn main() {
    // Create a vector with integers 1 to 5
    let numbers: Vec<i32> = (1..=5).collect(); // Use the collect() method to create a vector from a range

    // Iterate over the vector and print each element multiplied by 3
    for num in &numbers { // Iterate over a reference to the vector
        let result = num * 3; // Multiply each element by 3
        println!("{}", result); // Print the result
    }
}

Output:

3
6
9
12
15

Explanation:

Here is a brief explanation of the above Rust code:

  • fn main() {: This line defines the main function, which is the entry point of the program.
  • let numbers: Vec<i32> = (1..=5).collect();: This line creates a vector 'numbers' containing integers from 1 to 5 using the "collect()" method with a range (1..=5).
  • for num in &numbers {: This line starts a for loop that iterates over a reference to the vector 'numbers'.
  • let result = num * 3;: Inside the loop, each element 'num' of the vector is multiplied by 3, and the result is stored in the variable 'result'.
  • println!("{}", result);: Inside the loop, the result of the multiplication is printed using the "println" macro. This line is executed for each element of the vector.

Rust Code Editor:

Previous: Rust Vector access guide.
Next: Rust Vector sorting guide.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.