Bird
0
0

You want to write a Kotlin function that calculates factorial using a local recursive function. Which code correctly implements this?

hard📝 Application Q8 of 15
Kotlin - Functions
You want to write a Kotlin function that calculates factorial using a local recursive function. Which code correctly implements this?
Afun factorial(n: Int): Int { val fact = fun(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1) return fact(n) }
Bfun factorial(n: Int): Int { fun fact(x: Int) { if (x <= 1) 1 else x * fact(x - 1) } return fact(n) }
Cfun factorial(n: Int): Int { fun fact(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1) return fact(n) }
Dfun factorial(n: Int): Int { fun fact(x: Int): Int = if (x == 0) 0 else x * fact(x - 1) return fact(n) }
Step-by-Step Solution
Solution:
  1. Step 1: Check recursive local function syntax

    fun factorial(n: Int): Int { fun fact(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1) return fact(n) } correctly defines a local function fact with proper recursion and base case (x <= 1 returns 1).
  2. Step 2: Analyze other options

    B lacks return type and does not return value from fact. C uses val with recursive call which causes error because fact is not fully defined when called. D has wrong base case returning 0 for 0, which breaks factorial logic.
  3. Final Answer:

    fun factorial(n: Int): Int { fun fact(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1) return fact(n) } -> Option C
  4. Quick Check:

    Local recursive function = fun factorial(n: Int): Int { fun fact(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1) return fact(n) } [OK]
Quick Trick: Use local functions for recursion inside main function [OK]
Common Mistakes:
MISTAKES
  • Missing return in recursive function
  • Wrong base case in recursion
  • Using val for recursive local function causing errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes