Bird
Raised Fist0
R Programmingprogramming~10 mins

Recursive functions in R Programming - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Recursive functions
Call function with n
↓
Check base case: n == 1?
Yes→Return 1
No↓
Call function with n-1
↓
Wait for result
↓
Multiply n by result
↓
Return result
↓
Previous call resumes
↓
Final result returned
The function calls itself with a smaller input until it reaches the base case, then returns and combines results back up.
Execution Sample
R Programming
factorial <- function(n) {
  if (n == 1) {
    return(1)
  } else {
    return(n * factorial(n - 1))
  }
}
factorial(3)
Calculates factorial of 3 by calling itself with smaller numbers until 1.
Execution Table
StepCallnCondition (n==1?)ActionReturn Value
1factorial(3)3NoCall factorial(2)
2factorial(2)2NoCall factorial(1)
3factorial(1)1YesReturn 11
4factorial(2)2NoCalculate 2 * 12
5factorial(3)3NoCalculate 3 * 26
💡 Reached base case at n=1, then returned results back up the call stack.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
n332123
Return Value126
Key Moments - 3 Insights
Why does the function call itself with n-1 instead of just looping?
The execution_table shows at Step 1 and 2 that the function calls itself with smaller n to break the problem into simpler parts until the base case is reached.
What stops the recursion from going forever?
Step 3 in the execution_table shows the base case condition n==1 returns 1, stopping further recursive calls.
How does the function combine results from recursive calls?
Steps 4 and 5 show the function multiplies n by the returned value from the smaller call, building the final result back up.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the return value at Step 3?
A3
B2
C1
D6
💡 Hint
Check the 'Return Value' column at Step 3 where n=1 and base case returns 1.
At which step does the function first check the base case condition?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Condition (n==1?)' column to find when it is 'Yes'.
If we call factorial(4), how many total calls will appear in the execution_table?
A3
B4
C5
D6
💡 Hint
Each call reduces n by 1 until 1, so count calls from 4 down to 1.
Concept Snapshot
Recursive functions call themselves with smaller inputs.
They must have a base case to stop.
Each call waits for the smaller call's result.
Results combine as calls return.
Example: factorial(n) = n * factorial(n-1) with base case factorial(1)=1.
Full Transcript
This example shows how a recursive function works by calling itself with smaller inputs until it reaches a base case. The function factorial calls itself with n-1 until n equals 1. At that point, it returns 1. Then each previous call multiplies n by the returned value, building the final result. The execution table tracks each call, the condition check, and the return values step-by-step. The variable tracker shows how n and return values change during execution. Key moments clarify why recursion calls itself, how it stops, and how results combine. The quiz tests understanding of these steps.

Practice

(1/5)
1. What is the main purpose of a base case in a recursive function?
easy
A. To stop the recursion and prevent infinite calls
B. To call the function again with the same input
C. To increase the input size for the next call
D. To print the result of the recursion

Solution

  1. Step 1: Understand recursion basics

    A recursive function calls itself repeatedly with smaller inputs.
  2. Step 2: Identify the role of base case

    The base case stops the recursion to avoid infinite loops and eventual crash.
  3. Final Answer:

    To stop the recursion and prevent infinite calls -> Option A
  4. Quick Check:

    Base case = stop recursion [OK]
Hint: Base case always stops recursion to avoid infinite loops [OK]
Common Mistakes:
  • Forgetting the base case causes infinite recursion
  • Thinking base case calls function again
  • Confusing base case with recursive step
2. Which of the following is the correct syntax to define a recursive function fact in R that calculates factorial?
easy
A. fact <- function(n) { repeat n * fact(n - 1) }
B. fact <- function(n) { while(n > 0) n * fact(n - 1) }
C. fact <- function(n) { if(n == 1) n + fact(n - 1) }
D. fact <- function(n) { if(n == 0) 1 else n * fact(n - 1) }

Solution

  1. Step 1: Check base case and recursive call

    fact <- function(n) { if(n == 0) 1 else n * fact(n - 1) } correctly uses if condition for base case (n == 0) and recursive call with n-1.
  2. Step 2: Identify syntax errors in other options

    Options B, C, and D misuse loops or have wrong base case or missing else.
  3. Final Answer:

    fact <- function(n) { if(n == 0) 1 else n * fact(n - 1) } -> Option D
  4. Quick Check:

    Correct base case and recursive call syntax [OK]
Hint: Base case uses if, recursive call uses else with smaller input [OK]
Common Mistakes:
  • Using loops instead of recursion
  • Missing else leads to errors
  • Wrong base case condition
3. What is the output of this R code?
fib <- function(n) {
  if (n <= 1) return(n)
  else return(fib(n-1) + fib(n-2))
}
fib(4)
medium
A. 5
B. 4
C. 3
D. 7

Solution

  1. Step 1: Trace fib(4) calls

    fib(4) = fib(3) + fib(2); fib(3) = fib(2) + fib(1); fib(2) = fib(1) + fib(0)
  2. Step 2: Calculate values bottom-up

    fib(1)=1, fib(0)=0; fib(2)=1+0=1; fib(3)=1+1=2; fib(4)=2+1=3
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    Fibonacci(4) = 3 [OK]
Hint: Fibonacci(4) = 3 by adding previous two values [OK]
Common Mistakes:
  • Confusing index starting at 0 or 1
  • Adding wrong recursive calls
  • Forgetting base cases
4. Identify the error in this recursive R function to sum numbers from 1 to n:
sum_to_n <- function(n) {
  if (n == 1) return(1)
  else return(n + sum_to_n(n))
}
sum_to_n(3)
medium
A. The recursive call uses the same n, causing infinite recursion
B. The function should use a loop instead
C. The base case is missing
D. The return statement is outside the function

Solution

  1. Step 1: Check recursive call argument

    The function calls sum_to_n(n) instead of sum_to_n(n-1), so input never decreases.
  2. Step 2: Understand effect of error

    This causes infinite recursion because n stays the same and base case is never reached.
  3. Final Answer:

    The recursive call uses the same n, causing infinite recursion -> Option A
  4. Quick Check:

    Recursive call must reduce input [OK]
Hint: Recursive call must use smaller input to reach base case [OK]
Common Mistakes:
  • Calling function with same argument
  • Missing base case
  • Confusing recursion with loops
5. Write a recursive R function flatten_list that takes a nested list of numbers and returns a flat vector of all numbers.
What is the correct approach?
hard
A. Use recursion but forget to combine results from recursive calls
B. Check if input is a list; if yes, recursively flatten each element and combine; else return the element as vector
C. Return the input directly without any processing
D. Use a for loop to iterate and append elements without recursion

Solution

  1. Step 1: Identify recursive structure

    Nested lists require checking each element; if it's a list, call flatten_list recursively.
  2. Step 2: Combine results properly

    Combine all flattened elements into one vector to get a flat list of numbers.
  3. Final Answer:

    Check if input is a list; if yes, recursively flatten each element and combine; else return the element as vector -> Option B
  4. Quick Check:

    Recursion + combine results = flatten list [OK]
Hint: Recursively flatten each list element and combine results [OK]
Common Mistakes:
  • Not combining recursive results
  • Forgetting to check if element is a list
  • Using loops only without recursion
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard