How to check even numbers in Scala?

Member

by macie , in category: Other , 2 years ago

How to check even numbers in Scala?

Facebook Twitter LinkedIn Telegram Whatsapp

5 answers

Member

by jermain , 2 years ago

@macie Here is one line solution to print even numbers in Scala:


1
2
3
4
5
6
object HelloWorld {
    def main(args: Array[String]) {
        Array(25,2,12,6,5,31).foreach(e=>if(e%2==0)println(e));
        // Output: 2 12 6
    }
}

Member

by emma , 2 years ago

@macie If a number is evenly divisible by 2 with no remainder, then it is even. You can use % 2 to check if the reminder is 0 then it is an even number. Below is code in Scala on how to check numbers in an array:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
object HelloWorld {
    def main(args: Array[String]) {
        var arr = Array(25, 2, 12, 6, 5, 31)
        var i = 0

        // loop over numbers
        while(i < arr.size) {
            // check even number
            if(arr(i) % 2 == 0) {
                // if so output number
                println(arr(i))
            }
            i = i + 1
        }
        // Output: 2 12 6
    }
}
by janilcgarcia , a year ago

@macieWhile both of the provided solution do solve the problem, I think what looks more like Scala-style code would something in the lines of:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
val numbers = Array(25, 2, 12, 6, 5, 31) // I personally would use Vector, Seq or List here, actually

// With a for
for (number <- numbers) {
  if (number % 2 == 0)
    println(number)
}

// With a filtered for
for {
  n <- numbers
  if (n % 2 == 0)
} {
  println(n)
}

// With chained methods (my favorite for these kinds of situations)
numbers.withFilter(n => n % 2 == 0).foreach(println(_))

These approaches are more readable, contain less side-effects. I like the last especially because there is a separation in the processes: first filter, then print, but also you can add new operations after or before the filter as much you want, and sometimes that's important.


While this is also an acceptable solution:

1
2
3
4
numbers.foreach { n =>
  if (n % 2 == 0)
    println(n)
}

I find the for more explicit for these kinds of situations where the operation inside the block is being executed solely for purpose of a side-effect. I wouldn't but all of that in just a line like the other reply, though, as it does affect readability.

by hernan.javier.saab , a year ago

@macie Cmon, we can afford to be a bit more concise:


1
Array(25, 2, 12, 6, 5, 31).filter(_ % 2 == 0).foreach(println)

by august.kutch , a year ago

@macie What about this solution, guys?


1
Array(25,2,12,6,5,31).withFilter(_%2==0).foreach(println)