This is a program that finds the sum of odd numbers and the sum of even numbers in an array and displays the result. Follow the procedure below.
Main.java
class Main {
public static void main(String[] args) {
//Substitute the given array of numbers for the variable numbers
int[] numbers = {1, 4, 6, 9, 13, 16};
}
}
Main.java
class Main {
public static void main(String[] args) {
int[] numbers = {1, 4, 6, 9, 13, 16};
//Define the variable oddSum and assign 0(This is odd)
int oddSum = 0;
//Define the variable evenSum and assign 0(This is an even number)
int evenSum = 0;
}
}
As a processing procedure, while issuing all the arrays with the for statement, conditional branching is done with the if statement. By writing as follows, each element of the array numbers is assigned to the variable number in order.
Main.java
class Main {
public static void main(String[] args) {
int[] numbers = {1, 4, 6, 9, 13, 16};
int oddSum = 0;
int evenSum = 0;
//Repeat array numbers using for statement
for (int number : numbers) {
}
}
}
Let the description of (number% 2 == 0) determine whether it is an even number.
Main.java
class Main {
public static void main(String[] args) {
int[] numbers = {1, 4, 6, 9, 13, 16};
int oddSum = 0;
int evenSum = 0;
for (int number : numbers) {
//Describe conditional branch in if statement
if (number % 2 == 0) {
evenSum += number;
} else {
oddSum += number;
}
}
}
}
Describe it outside the for statement. If you write it in the for statement, it will be output every time you call each element of numbers.
Main.java
class Main {
public static void main(String[] args) {
int[] numbers = {1, 4, 6, 9, 13, 16};
int oddSum = 0;
int evenSum = 0;
for (int number : numbers) {
//Describe conditional branch in if statement
if (number % 2 == 0) {
evenSum += number;
} else {
oddSum += number;
}
}
//Described outside the for statement
System.out.println("The sum of odd numbers is" + oddSum + "is");
System.out.println("The sum of even numbers" + evenSum + "is");
}
}
That's it.
Recommended Posts