Task #1: Arrays and Methods
In this task, you are being asked to write a method that manipulates an array in Java.
Write a method called sumEvenOdd that accepts one integer array as argument and prints
the sum of all even and odd numbers in separate lines.
You may use the following header for this method:
static void sumEvenOdd(int[] array)
For example, if we pass {3, 2, 12, 15, 17, 22, 25, 26, 28} to this method,
then the method should print:
Sum of all even numbers: 90
Sum of all odd numbers: 60
NOTE: Declare and initialize the array without taking input from user.
1. Create a program called ArraySumEvenOddLab2.java
2. Correctly display appropriate messages.
public class ArraySumEvenOddLab2 {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
int[] array = { 3, 2, 12, 15, 17, 22, 25, 26, 28 };
sumEvenOdd(array);
}
static void sumEvenOdd(int[] array) {
int sumEvenNumbers = 0;
int sumOddNumbers = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
sumEvenNumbers += array[i];
} else {
sumOddNumbers += array[i];
}
}
System.out.println("Sum of all even numbers: " + sumEvenNumbers);
System.out.println("Sum of all odd numbers: " + sumOddNumbers);
}
}
Comments
Leave a comment