w3resource

Rust Program: Iterate over vector of integers

Rust Iterators and Iterator Adapters: Exercise-1 with Solution

Write a Rust program that iterates over a vector of integers and prints each element.

Sample Solution:

Rust Code:

fn main() {
    // Define a vector of integers
    let numbers = vec![100, 200, 300, 400, 500];

    // Iterate over the vector and print each element
    for number in &numbers {
        println!("{}", number);
    }
}

Output:

100
200
300
400
500

Explanation:

In the exercise above,

  • Define a vector 'numbers' containing integers.
  • Use a "for" loop to iterate over each element of the vector.
  • Within the loop, we print each element using "println!()".

Rust Code Editor:


Previous: Rust Iterators and Iterator Adapters Exercises.
Next: Rust Program: Calculate sum of range of numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-1.php