Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Loops

Exercise 1 integers

val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val squares = for n <- numbers yield n * n
println(squares)

Exercise 2 string lengths


val strings = List("apple", "banana", "cherry", "date", "elderberry")
val lengths = for s <- strings yield s.length
println(lengths)

Exercise 3 evens



val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evens = for n <- numbers if n % 2 == 0 yield n
println(evens)

Exercise 4 tuples

val people = List(("Alice", 25), ("Bob", 32), ("Charlie", 19), ("David", 42))
val youngNames = for 
    (name, age) <- people if age < 30 yield name
println(youngNames)

Exercise 5 string contains

val strings = List("apple", "banana", "cherry", "date", "elderberry")
val withA = for s <- strings if s.contains("a") yield s
println(withA)