w3resource

Kotlin Program: Count even and odd elements in an array


Write a Kotlin program to count the number of even and odd elements in an array.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Arrays.
  • Loops in Kotlin.
  • Modulo Operator.
  • Conditional Statements.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the Main Function.
  • Create an Array.
  • Count Even and Odd Numbers.
  • Return the Counts.
  • Display the Results.
  • Test with Different Arrays.
  • Common Errors to Avoid:
    • Forgetting to initialize counters.
    • Misplacing modulo logic.
    • Not iterating through all elements.

Sample Solution:

Kotlin Code:

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

    val evenCount = countEvenNumbers(numbers)
    val oddCount = countOddNumbers(numbers)

    println("Number of even elements: $evenCount")
    println("Number of odd elements: $oddCount")
}

fun countEvenNumbers(numbers: Array): Int {
    var count = 0

    for (number in numbers) {
        if (number % 2 == 0) {
            count++
        }
    }

    return count
}

fun countOddNumbers(numbers: Array): Int {
    var count = 0

    for (number in numbers) {
        if (number % 2 != 0) {
            count++
        }
    }

    return count
}

Sample Output:

Number of even elements: 6
Number of odd elements: 6

Explanation:

The "numbers" array contains the elements for which we want to count even and odd numbers.

  • The "countEvenNumbers()" function takes the numbers array as an argument and counts the number of even elements in the array.
  • Inside the "countEvenNumbers()" function, we initialize a variable count to hold the count of even numbers and set it to 0.
  • We use a for loop to iterate over each element in the numbers array.
  • For each element, we check if it is divisible by 2 (i.e., even) by using the condition number % 2 == 0. If it is, we increment the count variable.
  • After iterating through all the elements, we return the final count of even numbers.
  • The "countOddNumbers()" function is similar to countEvenNumbers(), but it counts odd elements instead.
  • In the main() function, we call "countEvenNumbers()" and "countOddNumbers()" with the numbers array and store the respective counts in evenCount and oddCount.
  • Finally, we print the counts of even and odd elements using println() function.

Go to:


PREV : Generate a multiplication table of a number.
NEXT : Find the GCD of two numbers.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.