Rust Program: Iterate over array and print elements
Rust Variables and Data Types: Exercise-8 with Solution
Write a Rust program that creates an array of numbers containing 5 integers. Iterate over the array and print each element.
Sample Solution:
Rust Code:
fn main() {
// Define an array of 5 integers
let numbers = [1, 2, 3, 4, 5];
// Iterate over the array and print each element
for &number in numbers.iter() {
println!("{}", number);
}
}
Output:
1 2 3 4 5
Explanation:
The above Rust code defines a main function that demonstrates how to iterate over an array of integers and print each element.
- fn main() { ... }: This declares the main function, which serves as the entry point of the program.
- let numbers = [1, 2, 3, 4, 5];: This line defines an array named 'numbers' containing five integers: 1, 2, 3, 4, and 5.
- for &number in numbers.iter() { ... }: This is a for loop that iterates over each element of the 'numbers' array using the "iter()" method. The loop variable '&number' is a reference to each element of the array. The '&' symbol before 'number' indicates that we are iterating over references to the elements rather than the elements themselves. This is because array elements in Rust are accessed by reference by default to prevent ownership transfer unless explicitly requested.
- println!("{}", number);: Inside the loop, this line prints each element of the array using the "println!" macro. The '{}' is a placeholder for the 'number' variable, which represents the current element being iterated over.
Rust Code Editor:
Previous: Rust: Print Latitude and Longitude separately.
Next: Rust Program: Define character variable with first initial.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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/basic/rust-variables-and-data-types-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics