**Problem Statement:**
Write a C# program that takes an array of integers as input and returns the sum of all even numbers in the array.
### Example:
Input: `[1, 2, 3, 4, 5]`
Output: `6` (since `2 + 4 = 6`)
### C# Solution:
csharp
using System;
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
// Call the function to get the sum of even numbers
int result = SumOfEvenNumbers(numbers);
Console.WriteLine("Sum of Even Numbers: " + result); // Output will be 6
}
static int SumOfEvenNumbers(int[] numbers)
{
int sum = 0;
foreach (int number in numbers)
{
if (number % 2 == 0) // Check if the number is even
sum += number;
}
return sum;
}
}
`
### Explanation:
1. **Main Method:**
- We define an array of integers `numbers`.
- Call the function `SumOfEvenNumbers` and store its result in a variable.
- Print out the sum of even numbers.
2. **SumOfEvenNumbers Function:**
- Initialize a variable `sum` to 0, which will hold the cumulative sum.
- Use a loop (`foreach`) through each number in the array.
- Inside the loop, check if the current number is even by using `number % 2 == 0`.
If it's true (i.e., an even number), add this number to our sum.
- After the loop, return the computed `sum`.
This solution iterates through each element in the array once and checks if it's even. If so, adds it to a running total of even numbers. Finally, returns this sum.
### Running the Code:
To run this code in your local environment:
1. Create a new C# Console Application project.
2. Replace or copy-paste the above code into Program.cs file of your newly created console application.
3. Run it, and you should see "Sum of Even Numbers: 6" printed in the output window.
This is a straightforward example to get started with basic C# programming.
Login to Continue, We will bring you back to this content 0