find the sum of all elements in an array in rust

Here's an example code block that demonstrates how to find the sum of all elements in an array in Rust using a loop and iteration:

main.rs
fn main() {
    let numbers: [i32; 5] = [4, 8, 15, 16, 23];

    let mut sum = 0;

    for num in numbers.iter() {
        sum += num;
    }

    println!("The sum is {}", sum);
}
180 chars
12 lines

In this code, we define an array of 5 integers and initialize it with some values. We then initialize a variable sum to 0. We then iterate over each element in the array using a for loop and add each element to the sum variable. Finally, we print out the value of sum.

This program will output The sum is 66.

related categories

gistlibby LogSnag