Sure, here is a Rust program to find the sum of all even numbers in a vector of integers:
Rust
fn sum_of_even_numbers(vector: &Vec<i32>) -> i32 {
// Initialize a sum variable.
let mut sum = 0;
// Iterate over the vector.
for number in vector {
// Check if the number is even.
if number % 2 == 0 {
// Add the number to the sum.
sum += number;
}
}
// Return the sum.
return sum;
}
fn main() {
// Create a vector of integers.
let vector = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Find the sum of all even numbers in the vector.
let sum = sum_of_even_numbers(&vector);
// Print the sum.
println!("The sum of all even numbers in the vector is: {}", sum);
}
This program first initializes a sum variable. The program then iterates over the vector. For each number in the vector, the program checks if the number is even. If the number is even, the program adds the number to the sum. Finally, the program returns the sum.
To run this program, you can save it as a .rs file and then compile and run it using the following commands:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust program to find the sum of all even numbers in a vector of integers:
Rust
This program first initializes a sum variable. The program then iterates over the vector. For each number in the vector, the program checks if the number is even. If the number is even, the program adds the number to the sum. Finally, the program returns the sum.
To run this program, you can save it as a
.rsfile and then compile and run it using the following commands:Code snippet
This will print the following output:
Code snippet
This indicates that the sum of all even numbers in the vector is 30.