Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Combining Functions and Control Flow | Functions and Control Flow
Introduction to Kotlin

bookCombining Functions and Control Flow

Swipe to show menu

Combining functions with control flow statements such as loops and conditionals lets you write more flexible and powerful Kotlin programs. When you place logic inside functions and use for or while loops along with if statements, your code becomes easier to read, test, and reuse. You can process collections of data, make decisions, and return results all within a single function. The following example shows how to structure code that uses a function to process a list, applies a loop to handle each item, and uses an if statement to perform conditional logic on each element.

Main.kt

Main.kt

copy
1234567891011121314151617
package com.example fun filterEvenNumbers(numbers: List<Int>): List<Int> { val result = mutableListOf<Int>() for (number in numbers) { if (number % 2 == 0) { result.add(number) } } return result } fun main() { val input = listOf(1, 2, 3, 4, 5, 6) val evens = filterEvenNumbers(input) println("Even numbers: $evens") }

In this code, the filterEvenNumbers function takes a list of integers as a parameter. Inside the function, a mutable list called result is created to hold the even numbers. The for loop goes through each number in the input list. The if statement checks if the current number is even by using the modulo operator (%). If the condition is true, the number is added to the result list. After the loop finishes, the function returns the list of even numbers. The main function demonstrates how to call filterEvenNumbers and print the result. This structure shows how you can combine functions, loops, and conditionals to process and filter data in Kotlin.

question mark

Which statement best describes how functions, loops, and conditionals work together in the provided Kotlin example?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 4

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

SectionΒ 3. ChapterΒ 4
some-alt