w3resource

Rust Array initialization guide

Rust Arrays: Exercise-1 with Solution

Write a Rust program to create an array of integers with size 7 and initialize it with values 1, 2, 3, 4, 5, 6 and 7. Print the array.

Sample Solution:

Rust Code:

fn main() {
    // Define an array with a size of 7 and initialize it with the specified values
    let arr: [i32; 7] = [1, 2, 3, 4, 5, 6, 7]; // Declare an array of type i32 (integer) with a size of 7 and initialize it with values

    // Print the array
    println!("Array: {:?}", arr); // Print the array using debug formatting
}

Output:

Array: [1, 2, 3, 4, 5, 6, 7]

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; 7] = [1, 2, 3, 4, 5, 6, 7];: This line declares an array named 'arr' of type i32 (integer) with a size of 7, and initializes it with the specified values [1, 2, 3, 4, 5, 6, 7].
  • println!("Array: {:?}", arr);: This line prints the array to the console. The {:?} syntax within the "println!" macro indicates that the array should be printed using its debug representation, which is suitable.

Rust Code Editor:

Previous: Rust Arrays Exercises.
Next: Rust Array access guide.

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/collections_and_data_structures/rust-arrays-exercise-1.php