Question:
How to count odd and even number from a series?

Summary:

Suppose we have an array of N elements in it. We have to separate the odd and even elements form the array separately using java.


Solution:

//User function Template for Java


class Solution

{

    public int[] countOddEven(int[] arr, int n)

    {

        int [] result = new int[2];

        int odd = 0, even = 0;


        for (int i : arr) {

            if (i%2 == 0)

                even++;

            else

                odd++;

        }

        result[0] = odd;

        result[1] = even;

        return result;

    }

}


Explanation:

This Java code defines a class named Solution with a public method countOddEven, which takes an array of integers arr and its length n as parameters. Inside the method:


  • It initializes an integer array result of size 2 to store the count of odd and even numbers.

  • It initializes two variables odd and even to store the count of odd and even numbers, respectively.

  • It iterates through each element of the input array arr.

  • For each element, it checks if it's even (i % 2 == 0). If so, it increments the even count; otherwise, it increments the odd count.

  • After iterating through all elements, it assigns the counts of odd and even numbers to the respective indices of the result array.

  • Finally, it returns the result array containing the counts of odd and even numbers.

In summary, this code calculates the counts of odd and even numbers in an input array and returns an array containing these counts.


Suggested blogs:

>How to route between different components in React.js?

>How to save python yaml and load a nested class?-Python

>How to send multiple HTML form fields to PHP arrays via Ajax?

>What is data binding in Angular?

>What is microservice architecture, and why is it better than monolithic architecture?

>What is pipe in Angular?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation


Ritu Singh

Ritu Singh

Submit
0 Answers