SDSnipDojo
← All lessons
Lesson 12 / 124 steps2 exercises

Final Challenges

Two classic warm-ups before you wrap up the course.

1. Putting it together

You've covered the building blocks — val and var, types, conditions, loops, functions, classes, collections, null safety, and lambdas. Time to combine them.

The next two tabs are classic exercises every Kotlin developer ends up writing at some point. They both come down to a small loop and a couple of var accumulators — no new concepts, just practice.

Take your time. There's no scaffolding this time — only the function signature and an empty body.

2. factorial

n! is the product of every positive integer from 1 up to n:

5! = 5 × 4 × 3 × 2 × 1 = 120
3! = 3 × 2 × 1 = 6

Implement factorial(n):

  • Start a var result = 1
  • Multiply it by every integer from 1 to n (or n down to 1 — same answer)
  • Return result

By convention, factorial(0) is 1 (the empty product).

Starter code

fun factorial(n: Int): Int {
    // Return n * (n - 1) * ... * 1
    // factorial(0) should return 1
    return 0
}

3. The Fibonacci sequence

The Fibonacci sequence starts 0, 1 and each next term is the sum of the previous two:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …

The recursive definition (fib(n) = fib(n-1) + fib(n-2)) is elegant but slow. The iterative version is much faster — keep two vars, slide them forward each step:

var a = 0
var b = 1
for (i in 2..n) {
    val next = a + b
    a = b
    b = next
}
// after the loop, b is the n-th Fibonacci number (for n ≥ 1)

You'll write this in the next step.

4. fibonacci

Implement fibonacci(n) returning the n-th Fibonacci number (0-indexed):

  • fibonacci(0) is 0
  • fibonacci(1) is 1
  • for n ≥ 2, fibonacci(n) is fibonacci(n - 1) + fibonacci(n - 2)

Use the iterative version from the previous step — handle n <= 0 and n == 1 early, then loop with two vars sliding forward.

Starter code

fun fibonacci(n: Int): Int {
    // 0, 1, 1, 2, 3, 5, 8, 13, ...
    // Return the n-th Fibonacci number (0-indexed).
    return 0
}

Run this Kotlin lesson in your browser

SnipDojo ships an in-browser Kotlin editor with the exercises above already wired to tests. Sign in with Google to edit the starter code, run it, and track your progress toward the free certificate — no installs and no local toolchain.

Sign in to run this code →