---
title: "Write a program to find the sum of all even numbers in a vector of integers in Rust."  
description: "Write a program to find the sum of all even numbers in a vector of integers in Rust."  
author: "Utpal Vishwas"  
published: 2023-06-20  
updated: 2023-06-24  
canonical: https://www.mindstick.com/forum/158798/write-a-program-to-find-the-sum-of-all-even-numbers-in-a-vector-of-integers-in-rust  
category: "rust"  
tags: ["programs"]  
reading_time: 2 minutes  

---

# Write a program to find the sum of all even numbers in a vector of integers in Rust.

Write a [program](https://www.mindstick.com/blog/12337/scaling-up-your-mentorship-program) to find the [sum](https://www.mindstick.com/forum/159332/how-can-i-use-sum-in-linq) of all even numbers in a [vector](https://www.mindstick.com/forum/33499/vector-vs-arraylist-which-has-better-performance-and-why) of integers in Rust.

## Replies

### Reply by Aryan Kumar

Sure, here is a Rust program to find the sum of all even numbers in a vector of integers:

Rust

```plaintext
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:

Code snippet

```plaintext
rustc sum_of_even_numbers.rs
./sum_of_even_numbers
```

This will print the following output:

Code snippet

```plaintext
The sum of all even numbers in the vector is: 30
```

This indicates that the sum of all even numbers in the vector is 30.


---

Original Source: https://www.mindstick.com/forum/158798/write-a-program-to-find-the-sum-of-all-even-numbers-in-a-vector-of-integers-in-rust

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
