Home > Back-end >  How to find product of odd and even numbers using Kotlin lambda expression
How to find product of odd and even numbers using Kotlin lambda expression

Time:02-19

How do I complete the given program code so that the program will ask the user to enter five integer numbers, only positive numbers will remain from the input numbers that will use to display the product of odd numbers and product of even numbers? In the context of lambda, I have the requirement to use forEach method.

fun main() {
    var nums = IntArray(5)
    var index = 0

    nums.forEach {
    // code to get input from the user
    }

    var prodOdd = 1
    var prodEven = 1

    nums.forEach {
    // code to accumulate the products of odd and even
    }

    println("The product of ${nums.filter { //some code } } is $prodEven")
    println("The product of ${nums.filter { //some code } } is $prodOdd")
}


GOAL / TEST CASES

Example Output 1
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
The product of [2, 4] is 8
The product of [1, 3, 5] is 15

Example Output 2
Enter number 1: 8
Enter number 2: 3
Enter number 3: 7
Enter number 4: 2
Enter number 5: 4
The product of [8, 2, 4] is 64
The product of [3, 7] is 21

Example Output 3
Enter number 1: 0
Enter number 2: 5
Enter number 3: 10
Enter number 4: 15
Enter number 5: 20
The product of [10, 20] is 200
The product of [5, 15] is 75

Example Output 4
Enter number 1: 3
Enter number 2: -6
Enter number 3: -4
Enter number 4: 8
Enter number 5: 2
The product of [8, 2] is 16
The product of [3] is 3

CodePudding user response:

Since the OP seems to be assigned homework, this is a slightly different solution not using the required forEach():

val numbers = mutableListOf<Int>()

while (true) {
  print("Enter number ${numbers.count()   1}: ")
  val input = readln()
  if (input.trim() == "" || input.toIntOrNull() == null) continue
  numbers.add(input.toInt())
  if (numbers.count() == 5) break
}

val evens = numbers.filter { it > 0 && it % 2 == 0 }
val odds = numbers.filter { it > 0 && it % 2 != 0 }

val productOfEvens = evens.reduce { acc, i -> acc * i }
val productOfOdds = odds.reduce { acc, i -> acc * i }

println("The product of $evens is $productOfEvens")
println("The product of $odds is $productOfOdds")
  • Related