w3resource

Rust Program: Printing array elements

Rust Basic: Exercise-9 with Solution

Write a Rust program that prints all elements of an array using a for loop.

Sample Solution:

Rust Code:

fn main() {
    // Define an array containing some elements
    let array = [1, 2, 3, 4, 5];

    // Start a for loop to iterate over each element of the array
    for element in array.iter() {
        // Print the current element
        println!("Element: {}", element);
    }
}

Output:

Element: 1
Element: 2
Element: 3
Element: 4
Element: 5

Explanation:

Here's a brief explanation of the above Rust code:

  • fn main() { ... }: This is the entry point of the program, where execution begins.
  • let array = [1, 2, 3, 4, 5];: This line defines an array named 'array' and initializes it with the elements [1, 2, 3, 4, 5].
  • for element in array.iter() { ... }: This line starts a "for" loop. The "iter()" method creates an iterator over the elements of the array. The loop will iterate over each element of the array, and for each iteration, the current element will be assigned to the variable 'element'.
  • println!("Element: {}", element);: This line prints the current element using the println! macro. The {} is a placeholder for the value of 'element', which is provided as an argument to the println! macro.

Rust Code Editor:

Previous: Rust Program: Printing even numbers.
Next: Rust Program: Factorial calculation.

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.