Rust Array Sum Guide
Write a Rust program to create an array of integers with size 7 and initialize it with random values. Calculate and print the sum of all the elements in the array.
Sample Solution:
Rust Code:
use rand::Rng; // Import the rand crate to generate random numbers
fn main() {
// Define an array with a size of 7 and initialize it with random values
let mut arr: [i32; 7] = [0; 7]; // Declare an array of type i32 (integer) with a size of 7 and initialize it with zeros
let mut rng = rand::thread_rng(); // Initialize the random number generator
for i in 0..7 { // Iterate over each index of the array
arr[i] = rng.gen_range(1..101); // Generate a random integer between 1 and 100 and assign it to the current index
}
// Calculate the sum of all elements in the array
let sum: i32 = arr.iter().sum(); // Use the sum() method on an iterator over the array elements to calculate the sum
// Print the sum of all elements in the array
println!("Sum of all elements of the said random numbers: {}", sum); // Print the sum to the console
}
Output:
Sum of all elements of the said random numbers: 294
Explanation:
Here is a brief explanation of the above Rust code:
- use rand::Rng;: This line imports the rand::Rng trait from the "rand" crate, which provides functions for generating random numbers.
- fn main() {: This line defines the main function, which is the entry point of the Rust program.
- let mut arr: [i32; 7] = [0; 7];: This line declares an array named 'arr' of type 'i32' (integer) with a size of 7 and initializes it with zeros.
- let mut rng = rand::thread_rng();: This line initializes the random number generator by creating a thread-local generator.
- for i in 0..7 { ... }: This line starts a for loop that iterates over each index of the array arr.
- arr[i] = rng.gen_range(1..101);: This line generates a random integer between 1 and 100 using the "gen_range()" method of the random number generator 'rng', and assigns it to the current index 'i' of the array 'arr'.
- let sum: i32 = arr.iter().sum();: This line calculates the sum of all elements in the array 'arr' using the sum() method on an iterator over the array elements.
- println!("Sum of all elements: {}", sum);: This line prints the sum of all elements in the array to the console.
Rust Code Editor:
Previous: Rust Array update guide.
Next: Rust Array Search Guide.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics