[Example]
Main.java
class Main {
public static void main(String[] args) {
int[] numbers = {1, 6, 11, 16, 21, 26};
int oddNumber = 0;
int evenNumber = 0;
for (int number : numbers) {
if (number % 2 == 0) {
evenNumber += number;
} else {
oddNumber += number;
}
}
System.out.println("The odd sum is" + oddNumber + "is");
System.out.println("Even sum is" + evenNumber + "is");
}
}
The above result is the sum of odd numbers is 33 Even sum is 48 It will be. Get the elements of the array numbers one by one and the value of that element is If it is odd, use the variable oddNumber If it is an even number, the variable evenNumber is used. "%" Is used in the if statement to determine whether it is an even number or an odd number. Is it even with k "even Number + = number;" by setting "% 2 == 0"? If not, else "oddNumber + = number;" will be executed.
Recommended Posts