ECE 264 • Midterm 2 Compact Study Guide
ECE 264 Midterm 2 Compact Study Guide
Advanced C Programming at Purdue
What this packet is built from
This guide is organized around the posted topic grouping: recursion, sorting, and linear data structures (lists,
queues, and stacks), with an extras section for high-yield GDB and debugging material.
It is compressed for open-note use: fast reference first, then the minimum explanation needed to actually solve
questions.
It is also tuned to the style of the attached midterms: short code-reading questions, fill-in-the-blank pointer fixes,
recursion/output tracing, merge-sort call counting, DFS bug reasoning, linked-list rewiring, and GDB stack tracing.
Exam feel
Highest-yield patterns
20 short questions, mostly
multiple choice / fill-in /
short code reasoning
Recursive trace or output, recurrence setup, merge-sort counts, quick-sort partition logic, linked-list
pointer updates, queue or stack behavior, DFS visited bug, and GDB stack tracing
How to use this during the exam: start with the quick-reference tables, then jump to the matching trap list or demo problem if the
question feels familiar but not identical.
1. Recursion
The posted review explicitly groups these under recursion: Tower of Hanoi, ball-selection variants, integer partition, binary search,
sorting, card shuffling, and depth-first search. The past exams also show recursive output tracing and recursion-focused GDB
questions.
Pattern
Core idea
What they usually test
Simple single-call recursion
Reduce to one smaller input until a base
case
Return value, base case, stack order
Two-call recursion
Split into two smaller calls
Printed order, count of outputs, count of function calls
Case-based recurrence
Break the first move into legal cases
Deriving f(n), choosing correct base cases
Recursion with extra
parameter
Carry a rule into the next call
Why you need parameters like min, index, or left
DFS / maze recursion
Try directions recursively and back out
Visited timing, direction order, and invalid-position
checks
Recursion checklist
• State exactly what the function means before doing anything. If you cannot say what f(n) or f(n, m) represents, the recurrence is
probably still fuzzy.
• Identify the base case first. Wrong base cases create wrong counts even when the recursive step looks correct.
• Separate printed output from returned value. Exams love this difference.
• When counting function calls, include the current call itself.
• When constraints affect future choices, expect an extra parameter.
Ball-selection recurrences
Page 1
ECE 264 • Midterm 2 Compact Study Guide
Scenario
Recurrence
Typical base
case
Why
R/B, no restriction
f(n) = 2f(n-1)
f(1) = 2
First ball is R or B
R/B, no two R consecutive
f(n) = f(n-1) + f(n-2)
f(1) = 2
Start with B, or start with RB
R/G/B, no two R consecutive
f(n) = 2f(n-1) + 2f(n-2)
f(1) = 3
Start with G/B, or start with R
then G/B
Do not memorize formulas blindly. The safe method is always: choose the first item, list the legal cases, then express each case in
terms of a smaller problem.
Integer partition
• Order matters: partitions like 1+3 and 3+1 are different unless the question says otherwise.
• Ascending-order version: you usually need an extra parameter such as min to enforce that later choices are larger. A standard
meaning is f(n, min) = number of ascending partitions of n using values at least min.
• Odd-only version: only subtract odd first choices, so the recurrence jumps by 1, 3, 5, ... rather than all positive integers.
• Big trap: “ascending order” and “order matters” are opposite ideas. Read that phrase very carefully.
/* ascending partition skeleton */
int f(int n, int min) {
if (n == 0) return 1;
int total = 0;
for (int i = min; i <= n; i++) {
total += f(n - i, i + 1);
}
return total;
}
Binary search as recursion
For maximum-step questions on a sorted array with no duplicates, the recurring idea is
f(n) = 1 + f(n/2),
f(1) = 1
because each comparison with the middle value removes about half of the remaining search space.
Tower of Hanoi
T(n) = 2T(n-1) + 1,
T(1) = 1
Interpretation: move n-1 disks away, move the largest disk once, then move the n-1 disks back on top.
Recursive trace patterns you should recognize instantly
Code shape
What to expect
return f(n-1) + f(n-2);
A recursion tree with fast-growing call count.
f(n-1); print(n); f(n-1);
In-order style print: left subtree, current value, right subtree.
print(n); f(n-1);
Output often goes from large to small.
f(n-1); print(n);
Output often goes from small to large.
Depth-first search / maze
• Check atEnd and invalid-position logic carefully. The standard safe order is: success case, invalid case, mark visited, try recursive
moves.
• If visited is set too late, the search can revisit the same square and loop forever.
• If the direction order changes, the path string can change even when the maze is still solvable.
Page 2
ECE 264 • Midterm 2 Compact Study Guide
• A DFS question is often really asking one of three things: does it terminate, what path is returned, or which bug causes the bad
behavior.
Recursion traps that have shown up before
Trap
Why it hurts
Forgetting +1 in call-count recurrences
g(n) counts the current call plus the recursive calls
Mixing prints with returns
A function can print many values but return only one
Missing extra parameter in constrained partition
problems
The recursive call loses the rule for future choices
Marking visited after recursion in DFS
Revisiting nodes can cause infinite recursion or wrong paths
Assuming base case only means n == 1
Some questions need n == 0, n < min, l >= r, or NULL
Recursion demo problems
R1. Output trace
Suppose a function does: if (n > 0) { func(n-2); printf("%d ", n); func(n-2); }. What is printed for n = 5, and how many
numbers are printed total?
R2. New recurrence
A bag contains unlimited B, G, and Y balls. No two G balls may be consecutive. Let f(n) be the number of valid
length-n sequences. Write a recurrence and a base case.
R3. Partition setup
Write a valid recursive meaning for f(n, m) if you want to count ascending partitions of n where the next chosen
number must be at least m. Then state the two most natural base cases.
R4. DFS bug reasoning
A maze solver checks bounds and walls first, but sets visited only after its loop over directions. What kind of failure
becomes possible, and why?
Page 3
ECE 264 • Midterm 2 Compact Study Guide
2. Sorting
The review materials narrow sorting to selection sort, merge sort, and quick sort. The attached exams show merge-sort call counting
and code reading, while the lecture review also shows recursive selection sort and a middle-pivot quick sort.
Algorithm
Core move
Time
Likely test angle
Selection sort
Find minimum of remaining part, swap to
front
O(n²)
One-pass state, recursive
version using arr + 1
Merge sort
Sort halves, then merge sorted halves
O(n log n)
Call counts, merge counts,
boundaries, helper memory
Quick sort
Partition around pivot, recurse left/right
Best/avg O(n log n),
worst O(n²)
Pivot final position, first
partition result, uneven splits
Recursive selection sort
void selection_sort(int* arr, int n) {
if (n == 1) return;
int m = 0;
for (int j = 1; j < n; j++)
if (arr[j] < arr[m]) m = j;
swap(arr, 0, m);
selection_sort(arr + 1, n - 1);
}
• arr + 1 means the next subarray starts one element later. It is not the same as arr[1].
• After one call, only the first position is guaranteed correct.
• Recursion does not change the asymptotic time. It is still O(n²).
Merge sort
mergeSort(arr, l, r):
if (l >= r) return;
m = (l + r) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
High-yield merge-sort facts
If n is a power of 2 and the recursion stops at size 1, then mergeSort call count = 2n - 1 and merge call count = n
- 1.
The shape of the recursion tree depends on array size, not on whether the input is already sorted. That is why a
sorted array usually does not change the mergeSort call count.
Common merge bugs: forgetting to copy leftovers, using wrong boundaries, or forgetting to free temporary memory.
Quick sort
Page 4
ECE 264 • Midterm 2 Compact Study Guide
/* middle element chosen as pivot index */
void quick_sort(int* arr, int l, int r) {
if (l < r) {
int pivotIndex = (l + r) / 2;
swap(arr, pivotIndex, l);
int pivot = arr[l];
int j = l;
for (int i = l + 1; i <= r; i++) {
if (arr[i] <= pivot) {
j++;
swap(arr, i, j);
}
}
swap(arr, l, j);
quick_sort(arr, l, j - 1);
quick_sort(arr, j + 1, r);
}
}
• After partitioning, the pivot is in its final sorted position at index j.
• The pivot should not be included again in either recursive call.
• Worst case happens when the splits are very uneven over and over again.
• Be careful about whether the partition condition is < pivot or <= pivot. That changes the exact movement of equal values.
Sorting traps
Trap
Fix / mental check
Off-by-one ranges in merge or quick sort
Write the exact subarray covered by each call before tracing
Thinking “already sorted” changes mergeSort call
count
It usually changes data movement, not the recursion tree
Confusing arr + 1 with arr[1]
One is a shifted pointer; the other is a single element
Re-sorting the pivot in quick sort
Recursive calls should skip the pivot’s final index
Sorting demo problems
S1. Merge-sort counts
For an array of size 16, how many times is mergeSort called and how many times is merge called, assuming the
usual base case l >= r? Would those numbers change if the array started already sorted?
S2. First quick-sort partition
A quick-sort implementation uses the middle index as pivot, swaps it to the front, then places every value <= pivot to
the left side. Starting from [7, 2, 9, 1, 5, 8, 3], what is the pivot and where does it end after the first partition?
S3. Selection-sort state
A recursive selection sort runs on [4, 1, 3, 2]. What must be true after the first call returns to its caller, even if the rest
of the array is not finished yet?
3. Linear Data Structures: Lists, Queues, and Stacks
The linked-list lecture is the biggest source here: node layout, empty list, insertion, search, delete, print, destroy, head/tail variants,
doubly linked lists, circular lists, sorted-list merge, plus stack and queue as linear structures. The previous exams repeatedly test tiny
pointer fixes rather than long code writing.
Core linked-list reference
Page 5
ECE 264 • Midterm 2 Compact Study Guide
Operation
Pattern
Cost
Most common mistake
Empty list
head = NULL
O(1)
Using an uninitialized head
Insert at head
new->next = head; head = new;
O(1)
Forgetting to store returned new head
Search
walk until NULL or match
O(n)
Stopping too late or dereferencing NULL
Delete by value
special-case head, otherwise reroute
prev->next
O(n)
Freeing before rerouting or forgetting head
case
Print
while (node != NULL)
O(n)
Assuming insertion order equals output order
Destroy
save next, free current, move on
O(n)
Reading node->next after free(node)
Minimal node forms
typedef struct listnode {
struct listnode * next;
int value;
} Node;
typedef struct {
Node * head;
Node * tail;
} LinkedList;
• A singly linked-list node needs at least a value and a pointer to the next node.
• An empty list is represented by NULL.
• With both head and tail, insertion at the end can be O(1).
Head insertion and return-value awareness
Node * List_insert(Node * head, int val) {
Node * ptr = Node_construct(val);
ptr->next = head;
return ptr;
}
/* caller must do: head = List_insert(head, val); */
If you call List_insert(head, 10); and ignore the return value, the list outside the function does not gain the new head pointer. This exact
idea has shown up before.
Delete and destroy patterns
Page 6
ECE 264 • Midterm 2 Compact Study Guide
Node * List_delete(Node * head, int val) {
Node * p = head;
if (p == NULL) return p;
if (p->value == val) {
p = p->next;
free(head);
return p;
}
Node * q = p->next;
while (q != NULL && q->value != val) {
p = p->next;
q = q->next;
}
if (q != NULL) {
p->next = q->next;
free(q);
}
return head;
}
void List_destroy(Node * head) {
while (head != NULL) {
Node * ptr = head->next;
free(head);
head = ptr;
}
}
• Deletion has two separate situations: deleting the first node and deleting a later node.
• In destroy, save the next pointer before freeing the current node.
• If the outer list structure itself was malloced, you also need to free that structure after freeing the nodes.
Tail-based list, queue, and stack
Structure
Fast operations with linked list
Key invariant
Stack (LIFO)
push at head, pop at head
Top is usually the head
Queue (FIFO)
enqueue at tail, dequeue at head
If last node is removed, both head and tail
become NULL
List with head + tail
insert at end in O(1)
tail->next points to the newly added node
Recursive merge of two sorted linked lists
Node* merge_sorted_list(Node* p, Node* q) {
Node* head = NULL;
if (p == NULL) return q;
if (q == NULL) return p;
if (p->value <= q->value) {
head = p;
head->next = merge_sorted_list(p->next, q);
}
else {
head = q;
head->next = merge_sorted_list(p, q->next);
}
return head;
}
• This function usually rewires links; it does not create brand-new nodes.
• Minimum link modifications happen when one entire list can stay mostly in front of the other.
• Maximum link modifications happen when the nodes alternate between the two lists as much as possible.
Linear-structure traps
Page 7
ECE 264 • Midterm 2 Compact Study Guide
Trap
What to remember
Forgetting head = returned_value
Head-insertion and head-deletion functions often return the new head
Missing NULL in print/search loops
NULL marks the end of a singly linked list
Breaking tail maintenance
After insert-at-end, tail must move to the new node
Queue becomes empty but tail is stale
Set both head and tail to NULL after removing the last element
Using freed memory
After free(node), do not read node->next or node->value
Linear-data-structure demo problems
L1. Head insertion output
A program starts with head = NULL, then does head = List_insert(head, 10); head = List_insert(head, 20); head =
List_insert(head, 30); then prints the list. What comes out, and why?
L2. Ignored return value
What happens if the same program instead calls List_insert(head, 10); without assigning the return value back to
head?
L3. Queue edge case
A queue stores head and tail. After one dequeue removes the only remaining node, what must happen to head and
tail?
L4. Sorted-list merge intuition
Two sorted lists are already separated so every value in list A is smaller than every value in list B. Is the number of
modified links during recursive merge closer to the minimum or the maximum? Explain briefly.
Page 8
ECE 264 • Midterm 2 Compact Study Guide
4. Extras
These topics are worth carrying into your notes even though they are outside the exact topic header in the screenshot, because the
posted review includes them and the previous midterms directly test them.
GDB for recursive programs
Command
What it does
Why it matters on this exam
b main
break at start of main
lets you step into the first recursive call
b func
break whenever func is entered
helps count calls and inspect n values
info b
show breakpoints and hit
counts
used in past midterm-style questions
n
step over
stay in current frame
s
step into
enter the next function call
bt
backtrace
shows the call stack and frame order
fk
jump to frame k
lets you inspect an older recursive frame
p var
print one variable
useful for current n, rtv, pointers
display var
auto-print a variable each stop
good for recursive tracing
GDB mental model
• Frame 0 is the current frame. Older calls have larger frame numbers.
• If main calls func(7), and the recursive step is func(n-2), then the values encountered are 7, 5, 3, 1.
• The breakpoint hit count at func usually equals the number of times the function started executing.
• A backtrace line shows both the argument value in that frame and the line where execution will return.
Pointer and memory micro-reference
Topic
Fast reminder
Stack vs heap
Local variables live on the stack; malloc creates memory on the heap
Leak
malloc without a matching free loses heap memory
Dangling pointer
pointer still points to freed memory
NULL
safe “points to nothing” marker for list ends and empty structures
struct pointer syntax
p->next is shorthand for (*p).next
Five-minute exam attack plan
• On recursion questions, write the first three calls or the first three legal cases before choosing an answer.
• On sorting questions, mark the exact subarray boundaries and pivot position.
• On list questions, draw boxes for nodes and arrows for next pointers. Tiny drawings prevent most mistakes.
• On GDB questions, follow the call chain with the actual argument values, not with vague labels like “next call”.
• If a question is fill-in-the-blank code, ask what pointer expression must preserve reachability of the structure.
5. Demo Problem Answer Key
These are intentionally brief so the guide stays compact.
R1. For n = 5, the call tree uses n = 5, 3, 1. The output is 1 3 1 5 1 3 1 and there are 7 numbers total.
Page 9
ECE 264 • Midterm 2 Compact Study Guide
R2. If the first ball is B or Y, there are 2f(n-1) continuations. If the first is G, the next cannot be G, so there are 2f(n-2) continuations.
One clean answer is f(n) = 2f(n-1) + 2f(n-2), with f(1) = 3.
R3. One valid meaning: f(n, m) counts ascending partitions of n where every future chosen number must be at least m. Natural base
cases: f(0, m) = 1 and f(n, m) = 0 for n < m.
R4. Infinite recursion or stack overflow becomes possible because the same open squares can be revisited before they are marked
visited.
S1. For n = 16: mergeSort calls = 2n - 1 = 31, merge calls = n - 1 = 15. Sorted input does not change those counts in ordinary merge
sort.
S2. Middle index is 3, so pivot value is 1. After swapping it to the front, every other value is > 1, so the pivot finishes at the leftmost
position.
S3. After the first call, the minimum element of the whole array is fixed at index 0.
L1. 30 20 10. Head insertion reverses the order of insertion when printed from head to tail.
L2. The insertion is lost outside the function because the caller never updates head to the new returned node.
L3. Set both head and tail to NULL.
L4. Closer to the minimum. The existing order already fits the final merged order with very little rewiring.
6. Source Reference
Primary source set used to tune this guide:
• 0324 Midterm 2 Review: open-note format, major topic list, recursive selection sort, quick sort outline, recursion examples, and GDB
reminders.
• 0220 Recursion (2): Tower of Hanoi, ball-selection recurrences, binary-search recurrence, merge-sort reasoning, and GDB/call-stack
examples.
• 0305 Linked List: node structure, empty list, insert/search/delete/print/destroy, head/tail list, circular list, doubly linked list, stack, and
queue.
• Previous Midterms (2019, 2020, 2021): GDB recursive tracing, odd-only integer partition, recursive print tracing, merge-sort call
counts, DFS visited bug, linked-list fill-ins, and recursive merge of sorted linked lists.
Page 10
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )