📖 Scenario: You are working on a program that calculates Fibonacci numbers. The Fibonacci sequence is a series where each number is the sum of the two before it, starting with 0 and 1.Calculating Fibonacci numbers using simple recursion can be very slow because it repeats the same calculations many times. To make it faster, you will use memoization, which means saving results of calculations so you don't repeat them.
🎯 Goal: Build a C program that uses memoization to optimize the recursive calculation of Fibonacci numbers. You will create a function that remembers past results to avoid repeated work.
📋 What You'll Learn
Create an integer array called memo to store results of Fibonacci calculations.
Create a recursive function called fib that takes an integer n and returns the nth Fibonacci number.
Use memoization inside the fib function to save and reuse results.
Print the Fibonacci number for n = 10.
💡 Why This Matters
🌍 Real World
Memoization is used in many real-world applications like caching web pages, optimizing game AI, and speeding up complex calculations.
💼 Career
Understanding memoization helps in writing efficient code, a key skill for software developers, especially in roles involving algorithms and performance optimization.
Progress0 / 4 steps
1
Create the memo array
Create an integer array called memo of size 11 and initialize all elements to -1.
DSA C
Hint
Use int memo[11] = { -1, -1, ..., -1 }; to create and initialize the array.
2
Create the fib function header
Create a recursive function called fib that takes an integer parameter n and returns an integer.
DSA C
Hint
Write int fib(int n) to start the function.
3
Implement memoization in fib function
Inside the fib function, add these steps: 1. If n is 0, return 0. 2. If n is 1, return 1. 3. If memo[n] is not -1, return memo[n]. 4. Otherwise, calculate fib(n-1) + fib(n-2), store it in memo[n], and return memo[n].
DSA C
Hint
Use if statements for base cases and check memo[n] before recursive calls.
4
Print the Fibonacci number for n = 10
In the main function, call fib(10) and print the result using printf.
DSA C
Hint
Use printf("%d\n", fib(10)); or store in a variable first.
Practice
(1/5)
1. What is the main purpose of using memoization in recursive functions?
easy
A. To avoid using any variables inside the function
B. To store results of expensive function calls and reuse them
C. To convert recursion into iteration automatically
D. To make the function run slower by adding extra steps
Solution
Step 1: Understand what memoization does
Memoization saves the results of function calls so they don't need to be recalculated.
Step 2: Identify the benefit in recursion
This reduces repeated work and speeds up recursive functions.
Final Answer:
To store results of expensive function calls and reuse them -> Option B
Quick Check:
Memoization = Store and reuse results [OK]
Hint: Memoization saves repeated results to speed recursion [OK]
Common Mistakes:
Thinking memoization slows down the function
Confusing memoization with converting recursion to loops
Believing memoization removes variables
2. Which of the following is the correct way to declare a memoization array for Fibonacci numbers in C?
easy
A. int memo[] = {1, 1};
B. int memo = 100;
C. int memo[100] = {0};
D. int memo(100);
Solution
Step 1: Check valid C array declaration
In C, arrays are declared with type, name, and size in square brackets.
Step 2: Identify correct syntax
int memo[100] = {0}; uses int memo[100] = {0}; which initializes all elements to zero correctly.
Final Answer:
int memo[100] = {0}; -> Option C
Quick Check:
Array declaration with size and initialization = int memo[100] = {0}; [OK]
Hint: Use int array[size] = {0} to initialize memo array [OK]
Common Mistakes:
Using parentheses instead of brackets for arrays
Assigning a single int instead of an array
Not initializing the array to zero
3. What will be the output of the following C code snippet using memoization for Fibonacci?
int memo[100] = {0};
int fib(int n) {
if (n <= 1) return n;
if (memo[n] != 0) return memo[n];
memo[n] = fib(n-1) + fib(n-2);
return memo[n];
}
int main() {
printf("%d", fib(5));
return 0;
}
medium
A. 5
B. 8
C. 3
D. 0
Solution
Step 1: Trace fib(5) with memoization
fib(5) = fib(4) + fib(3), and so on, with memo storing results to avoid repeats.
Hint: Remember fib(5) = 5 in Fibonacci sequence [OK]
Common Mistakes:
Confusing fib(5) with fib(6)
Ignoring memoization effect on output
Mistaking base cases
4. Identify the error in this memoized factorial function in C:
int memo[100] = {0};
int fact(int n) {
if (n == 0) return 1;
if (memo[n] != 0) return memo[n];
memo[n] = n * fact(n - 1);
return memo[n];
}
int main() {
printf("%d", fact(5));
return 0;
}
medium
A. Memo array is not initialized to -1 to detect uncalculated values
B. Base case should return 0 instead of 1
C. Function should use iteration, not recursion
D. Memo array size is too small
Solution
Step 1: Understand memo check condition
The code checks if memo[n] != 0 to decide if value is cached.
Step 2: Identify problem with zero initialization
Since factorial(0) = 1, memo[1] will be 0 initially, but 0 is a valid value for uninitialized. This causes confusion.
Step 3: Correct approach
Initialize memo array with -1 to mark uncalculated values, so 0 is a valid cached result.
Final Answer:
Memo array is not initialized to -1 to detect uncalculated values -> Option A
Quick Check:
Use -1 to mark uncalculated memo entries [OK]
Hint: Initialize memo with -1 to detect uncalculated values [OK]
Common Mistakes:
Assuming zero means uncalculated without initialization
Changing base case incorrectly
Thinking recursion must be replaced by iteration
5. You want to optimize a recursive function that calculates the number of ways to climb n stairs taking 1 or 2 steps at a time. Which memoization approach below correctly stores intermediate results to avoid repeated calculations?
hard
A. Use a global variable to count calls without storing results
B. Recalculate all values each time without storing
C. Use a linked list to store all previous results dynamically
D. Use an array int memo[n+1] initialized with -1, store results at memo[i] for steps i
Solution
Step 1: Understand problem and memoization need
Number of ways to climb stairs is a classic recursion problem with overlapping subproblems.
Step 2: Choose correct memoization method
Using an array sized n+1 initialized with -1 allows storing results for each step count to reuse.
Final Answer:
Use an array int memo[n+1] initialized with -1, store results at memo[i] for steps i -> Option D
Quick Check:
Array memo with -1 initialization stores intermediate results [OK]
Hint: Use array memo[n+1] with -1 to store step results [OK]
Common Mistakes:
Not initializing memo array properly
Using global counters without memoization
Using complex data structures unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.