Write a Java method sumEvenNumbers that takes an integer array as input and returns the sum of all even numbers in the array. The method should ignore any odd numbers in the array.
public class ArrayManipulation {
public static int sumEvenNumbers(int[] arr) {
// Your code here
}
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25, 30};
int sum = sumEvenNumbers(numbers);
System.out.println("Sum of even numbers: " + sum);
}
}
The sumEvenNumbers method can be implemented using a loop to traverse the array and conditionals to check for even numbers. Here's the step-by-step explanation:
public class ArrayManipulation {
public static int sumEvenNumbers(int[] arr) {
int sum = 0; // Variable to store the sum of even numbers
// Traverse the array
for (int i = 0; i < arr.length; i++) {
// Check if the current number is even
if (arr[i] % 2 == 0) {
// If even, add it to the sum
sum += arr[i];
}
}
// Return the sum of even numbers
return sum;
}
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25, 30};
int sum = sumEvenNumbers(numbers);
System.out.println("Sum of even numbers: " + sum);
}
}
In the sumEvenNumbers method, we start by initializing the variable sum to 0, which will store the sum of even numbers. Then, we use a for loop to traverse the array arr.
Inside the loop, we use a conditional statement if (arr[i] % 2 == 0) to check if the current number arr[i] is even. If it is even, we add it to the sum by using the += operator.
Finally, we return the sum as the result of the method. In the main method, we create an array numbers and call the sumEvenNumbers method passing numbers as the argument. The returned sum is then printed to the console using System.out.println.