Python Program to Count Even and Odd Elements in an Array.

Given an integer array of size n, the task is to write a Python program to count the numbers of even and odd elements present in the Array.

Example:
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
Even elements: 4
Odd elements: 5

Note: Any number that is divisible by 2 and gives us a remainder 0 is known as an even number and any number that is not divisible by 2 and gives us a remainder 1 is known as an odd number.

Algorithm to Count Even and Odd Numbers of Array.

Below are the steps of the algorithm that we need to follow to count even and odd elements of an array in Python programming.
  • Step 1: Initialize two counters, even_count and odd_count, to 0.
  • Step 2: Iterate through each element in the array.
  • Step 3: If the element is even (element % 2 == 0), increment even_count.
  • Step 4: If the element is odd (element % 2 != 0), increment odd_count.
  • Step 5: Print the counts of even and odd elements.

Python Code Implementation.
# Python program to count even and odd elements
def count_even_odd(arr):
    # Initialize counters
    even_count = 0
    odd_count = 0

    # Iterate through the array
    for num in arr:
        if num % 2 == 0:
            even_count += 1
        else:
            odd_count += 1

    # Display the result
    print("Even elements:", even_count)
    print("Odd elements:", odd_count)

# Example usage
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
count_even_odd(array)
Output:
Even elements: 4
Odd elements: 5
  • Time Complexity: O(n) where n is the size of the given array.
  • Space Complexity: O(1) as a constant amount of extra space is used.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS