[Java] [Memorandum] Java Output of sum of odd and even elements

2 minute read

Introduction

I went to a programming school in February of this year and started working at an IT company in July. I wanted to start posting articles because I wanted to output the language I learned! This time, I will post an article about Java that I did not study at programming school.

Development environment

This time, I tried it in the integrated development environment called “Eclipse”. Please try to build a development environment with reference to this article.

Create a Java development environment with Eclipse (Mac) *This time, it will be work on Mac.

Implementation


class Main {
  public static void main(String[] args) {

    int[] numbers = {1, 5, 8, 10, 13, 18};
    int oddSum = 0;
    int evenSum = 0;

    for (int number: numbers) {
      if (number %2 == 0) {
        evenSum += number;
      } else {
        oddSum += number;
      }
    }

    System.out.println("The sum of odd numbers is "+ oddSum + "");
    System.out.println("The sum of even numbers is "+ evenSum + "");
  }
}

The above code is explained from top to bottom!

Define the main method in the Main class.

class Main {
  public static void main(String[] args) {

Write some favorite integers in the variable number in an array with int type elements.

int[] numbers = {1, 5, 8, 10, 13, 18};

▽ Define variables oddSum and evenSum in int type and put 0 in both variables. *OddSum means an odd sum, and evenSum means an even sum.

int oddSum = 0;
int evenSum = 0;

The for statement makes iterative processing and the if statement creates a conditional branch. This time, we will use the “extended for statement”.

for (data type variable: array name) {
    Iterative processing;
}

In the statement, enter int type variable number and array numbers. In the if statement, add a condition such as “when number is an even number”.

  • += means that in the case of a += b, it is the same as a = a + b.
for (int number: numbers) {
      if (number %2 == 0) {
        evenSum += number;
      } else {
        oddSum += number;
      }
}

Finally, I will output it!


System.out.println("The sum of odd numbers is "+ oddSum + "");
System.out.println("The sum of even numbers is "+ evenSum + "");

Don’t forget the closing brackets for the Main class and main method! ]

 }
}

Execute

execution result


Odd sum is 19
The sum of even numbers is 36

If it is displayed, it is successful!

If you get an error

I think that there is a possibility that ; is missing, so please check it!

Finally

Everyone who is studying programming, although I am studying rave reviews, Let’s work together so that we can be patient and have fun coding! Thank you for watching until the end! ! !

Tags:

Updated: