w3resource

Rust Array update guide

Rust Arrays: Exercise-3 with Solution

Write a Rust program to create an array of characters with size 6 and initialize it with the characters 'A', 'B', 'C', 'D', 'E', and 'F'. Update the element at index 3 to 'P' and print the updated array.

Sample Solution:

Rust Code:

fn main() {
    // Define an array with a size of 6 and initialize it with characters
    let mut arr: [char; 6] = ['A', 'B', 'C', 'D', 'E', 'F']; // Declare an array of type char (character) with a size of 6 and initialize it with characters

    // Update the element at index 3 to 'P'
    arr[3] = 'P'; // Update the value at index 3 of the array to 'P'

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

Output:

Updated Array: ['A', 'B', 'C', 'P', 'E', 'F']

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 mut arr: [char; 6] = ['A', 'B', 'C', 'D', 'E', 'F'];: This line declares an array named 'arr' of type char (character) with a size of 6, and initializes it with the characters 'A', 'B', 'C', 'D', 'E', and 'F'.
  • arr[3] = 'P';: This line updates the value at index 3 of the array 'arr' to 'P'. The value at index 3 is accessed using the indexing syntax 'arr[3]', and it is assigned the value 'P'.
  • println!("Updated Array: {:?}", arr);: This line prints the updated array to the console. The {:?} syntax within the "println!" macro indicates that the array should be printed using its debug representation, which is suitable for printing arrays.

Rust Code Editor:

Previous: Rust Array access guide.
Next: Rust Array Sum 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-3.php