w3resource

Anonymous Kotlin function: Sum of odd numbers in a list


Write an anonymous Kotlin function to calculate the sum of all odd numbers in a list.


Pre-Knowledge (Before You Start!)

Before solving this exercise, you should be familiar with the following concepts:

  • Lists: A list in Kotlin is an ordered collection of elements. Here, we are working with a list of integers.
  • Anonymous Functions: Anonymous functions in Kotlin allow us to define functions without explicitly naming them. These functions can be assigned to variables.
  • Loops: Understanding how to iterate over a list using a for loop is essential to process each element.
  • Modulo Operator (%): The modulo operator is used to determine whether a number is even or odd. If number % 2 != 0, the number is odd.
  • Conditional Statements: You need to use an if condition to check if a number is odd before adding it to the sum.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: Define an anonymous function that takes a list of integers as a parameter and returns an integer.
  • Hint 2: Initialize a variable to store the sum of odd numbers, starting at 0.
  • Hint 3: Iterate through the list using a for loop.
  • Hint 4: Check if a number is odd using number % 2 != 0. If true, add it to the sum.
  • Hint 5: Return the final sum after iterating through all numbers in the list.

Sample Solution:

Kotlin Code:

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

    val sumOfOdds: (List<Int>) -> Int = fun(list: List<Int>): Int {
        var sum = 0
        for (number in list) {
            if (number % 2 != 0) {
                sum += number
            }
        }
        return sum
    }

    val oddSum = sumOfOdds(numbers)
    println("Original list of elements: $numbers")
    println("Sum of odd numbers: $oddSum")
}

Sample Output:

Original list of elements: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Sum of odd numbers: 36

Explanation:

In the above exercise -

  • We define an anonymous function called sumOfOdds with the type (List<Int>) -> Int. It takes a list of integers as its parameter and returns the sum of all odd numbers in the list as an integer.
  • Inside the sumOfOdds function, we initialize a variable sum to keep track of the sum, initially set to 0.
  • We iterate through each number in the input list using a for loop. If a number is odd (i.e., not divisible by 2), we add it to the sum variable.
  • In the end, we return the sum of all odd numbers in the list, which represents the final value of sum.

Go to:


PREV : Count vowels in a string.
NEXT : Concatenation of two strings.

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.