w3resource

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

Scala Programming Array Exercise-23 with Solution

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

Scala Code Editor :

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

Previous: 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.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/array/scala-array-exercise-23.php