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

bookCombining Functions and Control Flow

Svep för att visa menyn

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

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 4

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 3. Kapitel 4
some-alt