Rust Array access guide
Rust Arrays: Exercise-2 with Solution
Write a Rust program to create an array of integers with size 9 and initialize it with any value. Access and print the element at index 7.
Sample Solution:
Rust Code:
fn main() {
// Define an array with a size of 9 and initialize it with arbitrary values
let arr: [i32; 9] = [10, 20, 30, 40, 50, 60, 70, 80, 90]; // Declare an array of type i32 (integer) with a size of 9 and initialize it with arbitrary values
// Access and print the element at index 7
println!("Element at index 7: {}", arr[7]); // Print the value at index 7 of the array
}
Output:
Element at index 7: 80
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 Rust program.
- let arr: [i32; 9] = [10, 20, 30, 40, 50, 60, 70, 80, 90];: This line declares an array named arr of type i32 (integer) with a size of 9, and initializes it with arbitrary values [10, 20, 30, 40, 50, 60, 70, 80, 90].
- println!("Element at index 7: {}", arr[7]);: This line accesses and prints the element at index 7 of the array 'arr'. The value at index 7 is accessed using the indexing syntax 'arr[7]', and it is printed using the 'println!' macro. 1. fn main() {: This line defines the main function, which is the entry point of the Rust program. 2. let arr: [i32; 9] = [10, 20, 30, 40, 50, 60, 70, 80, 90];: This line declares an array named arr of type i32 (integer) with a size of 9, and initializes it with arbitrary values [10, 20, 30, 40, 50, 60, 70, 80, 90]. 3. println!("Element at index 7: {}", arr[7]);: This line accesses and prints the element at index 7 of the array 'arr'. The value at index 7 is accessed using the indexing syntax 'arr[7]', and it is printed using the 'println!' macro.
Rust Code Editor:
Previous: Rust Array initialization guide.
Next: Rust Array update guide.
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://www.w3resource.com/rust/collections_and_data_structures/rust-arrays-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics