w3resource

Scala Programming: Find the number of even and odd integers in a given array of integers


Write a Scala program to find the number of even and odd integers in a given array of integers.

Sample Solution:

Scala Code:

object scala_basic {

  def main(args: Array[String]): Unit = {
    var array_nums = Array(5, 7, 2, 4, 9)
    println("Original array:")
    for (x <- array_nums) {
      print(s"${x}, ")
    }

    var ctr = 0;
    for (i <- 0 to array_nums.length - 1) {
      if (array_nums(i) % 2 == 0)
        ctr=ctr+1
    }
      println("\nNumber of even numbers : " + ctr);
      println("Number of odd numbers  : " + (array_nums.length - ctr));
   }
}

Sample Output:

Original array:
5, 7, 2, 4, 9, 
Number of even numbers : 2
Number of odd numbers  : 3

Go to:


PREV : Write a Scala program to find a missing number in an array of integers.
NEXT : Write a Scala program to get the difference between the largest and smallest values in an array of integers. The length of the array must be 1 and above.

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.