VelocerBuka aplikasi

Velocer › Flashcard › University of Wisconsin–Madison › comp sci 300 full course review

comp sci 300 full course review

For comp sci 300 exam review. · oleh lake_street_ramp_cards · 591 kartu

University of Wisconsin–Madison

Pelajari dek ini Sematkan

  1. GraphNodes (vertices) plus edges (arcs); a tree is a graph, but a graph need not be a tree.
  2. How does a graph differ from a tree in incoming edges?A graph allows any number of incoming edges per node; a tree allows at most one.
  3. Directed graphEdges are arrows, so you travel one way only and can hit dead ends.
  4. Undirected graphEdges are plain lines, so you can travel either way.
  5. Self-loopAn edge from a node to itself.
  6. Adjacent nodesTwo nodes joined by an edge, like 2 and 1 in edge 2→1.
  7. Predecessor and successorIn edge 2→1, 2 is the predecessor of 1 and 1 is the successor of 2.
  8. Source and targetIn edge 2→1, 2 is the source and 1 is the target.
  9. PathA sequence of nodes linked by edges, like 2→1→5.
  10. Acyclic vs. cyclic pathAcyclic repeats no node; cyclic has some node appear twice.
  11. DAGA directed acyclic graph: directed edges and no cycles.
  12. Complete graphAn edge between every pair of nodes; directed version has edges both ways for every pair.
  13. Weighted graphValues on edges (cost, length, time); can be directed or undirected.
  14. Connected (undirected graph)There is a path between every pair of nodes.
  15. Strongly connected (directed graph)You can get from any node to any other node by following arrows. Example: u → v and v → u means u and v are strongly connected.
  16. Weakly connected (directed graph)It is connected when you treat the edges as undirected.
  17. Does strongly connected imply weakly connected?Yes, but weakly connected does not imply strongly connected.
  18. What do nodes and edges model in a graph?Nodes are objects; edges are relationships between them.
  19. How do you store a graph with no root?The Graph holds a collection (array, List, or Set) of nodes.
  20. What does each graph node store?Its data plus pointers to its successors (array, List, or Set).
  21. How are weights stored in a weighted graph?With each edge, for example inside the successor entries.
  22. Depth-first search (DFS)Go as deep as possible before backtracking.
  23. Why mark nodes visited in DFS?To avoid infinite loops when the graph has cycles.
  24. DFS algorithm stepsMark n visited, then recurse on each unvisited successor.
  25. How can you store the visited flag?A boolean field per node, or an array of size N for nodes numbered 1..N.
  26. What determines DFS visit order?The order of the successors.
  27. DFS worst-case timeO(N + E) for N nodes and E edges.
  28. How do you test whether a path j→k exists?Clear marks, run dfs(j); a path exists iff k is visited.
  29. Why is a 2-state visited flag not enough for cycle detection?You also need an IN_PROGRESS state to spot a successor still being explored.
  30. When is a cycle reachable from n detected in DFS?When a successor is found IN_PROGRESS during dfs(n).
  31. Does a DONE successor indicate a cycle?No; only an IN_PROGRESS successor does.
  32. How do you check the whole graph for cycles?Call hasCycle on each node that is still unvisited.
  33. Topological numbering ruleFor every edge j→k, number(j) < number(k).
  34. How is a topological number assigned?Assign N to a node with no outgoing edges, then work downward.
  35. When does a node get its topological number?After all its successors are numbered, at the DONE point.
  36. What happens if you request a topological order on a cyclic graph?No ordering exists, so you throw an exception.
  37. Breadth-first search (BFS)Visit all nodes at distance d before any node at distance d+1.
  38. What data structure does BFS use?A queue; DFS uses recursion or a stack.
  39. BFS algorithm stepsMark start visited and enqueue it; dequeue current, enqueue unvisited successors while marking them.
  40. On a tree, what is BFS equivalent to?Level-order traversal.
  41. Input vs. outputInput is info the program needs to run; output is info it sends to the user.
  42. What is System.out?A PrintStream instance, which is a Stream type.
  43. What three streams does System create at startup?System.in, System.out, and System.err.
  44. What prints when an object has no toString override?ClassName@hexhashcode, like Wanderer@13fac.
  45. OverrideProvide the same visibility and signature as an inherited method.
  46. Stream objectConnects your program to an I/O device.
  47. What does a Reader add, and what does a Printer add?A Reader adds input functionality; a Printer adds output functionality.
  48. Which class reads keyboard input?java.util.Scanner.
  49. Which class writes text to a file?java.io.PrintWriter.
  50. Why only one Scanner per System.in?Multiple Scanners break the input order; put one at the start of main or make it static.
  51. What does nextLine() always return?A String, even for input like "123".
  52. How do you turn input text into an int?Integer.parseInt(input).
  53. What is Integer?A wrapper class with parsing methods that stores a primitive int as an object.
  54. What must you do when creating a Scanner on a File?Handle the checked IOException by catching it or adding throws IOException to the method header.
  55. ADTSeparates the specification (what it is and its allowed operations) from the implementation (how it's built).
  56. What runs first in a try/catch/finally?The try block runs first.
  57. What runs after the try block if an exception matches a catch?The matching catch block runs next.
  58. Does finally always run?Yes, finally runs every time the try executes, even if an exception escapes.
  59. What happens to code after an uncaught exception?Execution stops; nothing after it prints.
  60. If a catch rethrows, what happens to later catches in the same try?They are skipped.
  61. How many catch blocks execute for one exception?Only the first matching catch executes.
  62. Why does catch order matter?A subclass catch must come before its superclass catch, or the subclass one never runs.
  63. Where does a rethrown exception go?It propagates to the caller, not to sibling catches in the same try.
  64. Which exceptions must be declared in a throws clause?Only checked exceptions.
  65. Do unchecked exceptions need a throws declaration?No, the compiler does not require it.
  66. ArithmeticException: checked or unchecked?Unchecked.
  67. StringIndexOutOfBoundsException: checked or unchecked?Unchecked.
  68. NullPointerException: checked or unchecked?Unchecked.
  69. InternalError: is it an Exception?No, it is an Error, a separate branch of Throwable.
  70. Is finally skipped when an exception is thrown?No, finally still runs.
  71. Which exceptions require a throws clause: checked or unchecked?Only checked exceptions require it.
  72. Is Error a subclass of Exception?No, Error and Exception are separate branches of Throwable.
  73. What can an undetected logical error become?A low-level runtime error.
  74. User error vs programmer bugUser error: anticipate it, like reprompting for a filename. Programmer bug: detect early, maybe save data.
  75. Why pass an error up instead of handling it where it occurs?Recovery is often impossible at that level, so pass it to a level that can handle it.
  76. Print message and quit: drawback?No recovery.
  77. Return special value: main drawback?Fails when all return values are valid, and the caller may skip the check.
  78. Return special value: effect on code?Makes code clumsy: f(g(x)) becomes ret = g(x); if...
  79. Reference param or global error code: what does it fix?It fixes the no-special-value problem, but not the other two drawbacks.
  80. Preferred error-handling approach in modern languages?Exceptions.
  81. What does throw do to the current code?It stops the current code and sends control to a matching catch in the first enclosing try.
  82. Where can the matching try be?In the same method or in a caller; otherwise the exception propagates up the call chain.
  83. What happens if an exception is uncaught past main?The JVM prints a message and the program stops.
  84. How many catch clauses per exception type?One catch per exception type.
  85. How does a catch name the exception?Like a parameter, e.g. catch (IOException e).
  86. What is finally used for?Cleanup, like closing files.
  87. Can you have zero catch clauses?Yes, if you have a finally block.
  88. What if a checked exception has no catch?The code won't compile unless the method declares it in throws.
  89. Checked exception: what must you do?Declare it in a throws clause or wrap it in a try with a matching catch.
  90. Who enforces checked exceptions?The compiler.
  91. Subclass of RuntimeException: checked or unchecked?Unchecked.
  92. Subclass of Exception but not RuntimeException: checked or unchecked?Checked.
  93. Are I/O exceptions like FileNotFoundException checked or unchecked?Checked.
  94. Are most built-in exceptions like NullPointerException checked or unchecked?Unchecked.
  95. User-defined exceptions: which type do they usually extend?Exception, making them checked.
  96. Your method calls one that might throw. What are your 3 options?Catch and handle it; catch it then rethrow; ignore it so it propagates up.
  97. What must a method list in throws?Every checked exception it throws or lets escape.
  98. throws clause syntaxvoid m() throws Ex1, Ex2 { ... }
  99. How do you define an exception class?Extend Throwable, usually Exception; an empty body is enough.
  100. Empty exception class exampleclass EmptyStackException extends Exception { }
  101. How do you add a message to an exception?Add a String constructor that calls super(message); retrieve it with getMessage().
  102. How do you throw an exception?Use throw new ExType(...); you must use new because exceptions are objects.
  103. What does throwing a checked exception require?It must be in the method's throws clause.
  104. Which frames does an exception skip?Frames whose catch types don't match; the first matching catch wins.
  105. throw vs throwsthrow is a statement that raises an exception; throws is a declaration on a method.
  106. Does checked mean serious?No, checked means compiler-enforced.
  107. What happens if you rethrow a different exception type?It changes which handler catches it.
  108. List ADTAn ordered collection of items of element type E, each with a position starting at 0.
  109. In a List, what does "ordered" mean?Each item has a position starting at 0; it does NOT mean sorted.
  110. External vs. internal view of an ADTExternal is the conceptual picture and operations; internal is the implementation.
  111. add(E item)Appends the item to the end of the list.
  112. add(int pos, E item)Inserts at pos, shifting items pos..size()-1 right; error if pos < 0 or pos > size().
  113. contains(E item)True iff some element x in the list satisfies x.equals(item).
  114. size()Returns the number of items in the list.
  115. isEmpty()True iff the size is 0.
  116. get(int pos)Returns the item at pos; error if pos < 0 or pos ≥ size().
  117. remove(int pos)Removes and returns item at pos, shifting later items left; error if pos < 0 or pos ≥ size().
  118. Is add at pos = size() legal?Yes, it appends. But get or remove at size() is not legal.
  119. Are interface members public?Yes, everything in an interface is public; the public keyword is optional.
  120. How does a class implement an interface?Add "implements InterfaceName" to the declaration and define each method with the exact same signature.
  121. How do array and List sizes differ?An array's size is fixed at creation; a List grows by 1 per add and shrinks by 1 per remove.
  122. Why is List<int> a compile error?A List holds only Objects, not primitives; use the wrapper class Integer instead.
  123. Auto-boxingJava automatically converts between a primitive and its wrapper, like int ↔ Integer.
  124. Raw List get returns what type?Object, so you must downcast, e.g. (String)list.get(0); a wrong type throws ClassCastException.
  125. SimpleArrayList fieldsObject[] items and int numItems.
  126. SimpleArrayList constructorSets numItems = 0 and items = new Object[INITSIZE], where INITSIZE is 10.
  127. Trade-off of a larger initial array sizeFewer expansions, but wasted memory if the array stays unfilled.
  128. SimpleArrayList add(item) stepsExpand if full, store at items[numItems], then numItems++.
  129. What does expandArray do?Makes a new array of size numItems*2, copies items over, and reassigns items.
  130. add(pos, item) steps in an array listCheck pos, expand if full, shift items pos..numItems-1 right, store at pos, numItems++.
  131. When should a method throw an exception?For errors it can't handle; don't use exceptions for control flow like loop exit.
  132. IteratorA "finger" that points at items in turn, starting at the first item.
  133. next()Returns the pointed item and advances the pointer; past the end throws NoSuchElementException.
  134. hasNext()True if items remain to be visited.
  135. How do you get an iterator?Iterable and Collection classes provide an iterator() method.
  136. For-each loop over a listfor (String w : words) — the colon reads as "in".
  137. How do you implement an iterator?Use a separate class holding the list and a current index curPos starting at 0.
  138. Iterator hasNext and next logichasNext: curPos < list.size(). next: throw NoSuchElementException if none, else get(curPos), curPos++, return.
  139. Iterator remove() when unimplementedThrow UnsupportedOperationException.
  140. Iterator remove() when implementedRemoves the last item returned by next; otherwise throw IllegalStateException.
  141. Black-box testingTesting from the spec with no knowledge of the implementation.
  142. Black-box test checklistCall every operation; test 0, 1, many items; test boundary and illegal inputs like pos -1 or remove at size().
  143. White-box testingTesting with knowledge of the code; the goal is every line executes at least once.
  144. White-box example for an array listForce the array to fill so expandArray actually runs.
  145. Why might black-box testers miss expansion?They don't know arrays are used, so they may never fill the array enough to trigger it.
  146. while loop over a listDeclare pos = 0 before, test pos < length in the condition, increment inside the body.
  147. What must remove(int pos) do first?Validate that pos is in range, rejecting a bad pos before any shifting.
  148. Does 'ordered' in a List mean sorted?No. It means each item has a position, not that items are in sorted order.
  149. Why can add use pos == size() but get cannot?add can place an item in the next empty slot; get can't read a slot that doesn't exist yet.
  150. Why use an interface for a list?It separates the public interface from the private implementation, so clients don't see the implementation.
  151. List vs array: sizeA list's size changes dynamically (+1 per add, −1 per remove); an array's size is fixed at creation.
  152. Why can't you write List<int> in Java?Lists hold only Objects, not primitives; use the wrapper class Integer instead.
  153. Wrapper classA class that holds one primitive value, like Integer holding an int.
  154. Why downcast a raw List get result?A raw List returns Object, so you cast it, e.g. (String)list.get(0); a wrong type throws ClassCastException.
  155. Fields of an array-based listObject[] items and int numItems.
  156. What does the array-based list constructor do?Sets numItems = 0 and creates items = new Object[INITSIZE], where INITSIZE is 10.
  157. add(item) on a full arrayCalls expandArray first, then stores items[numItems] = item and increments numItems.
  158. expandArrayA private method that makes a new array of size numItems*2, copies the items, and replaces the reference.
  159. Steps of add(pos, item)Check pos range, expand if full, shift items pos..numItems-1 right, store at pos, increment numItems.
  160. What happens if next() is called past the end?It throws NoSuchElementException.
  161. Fields of a separate iterator classA reference to the list and the current index.
  162. Methods the Iterator interface requireshasNext, next, and remove.
  163. How does hasNext work?Returns curPos < list.size().
  164. How does next work?Throw if !hasNext, else get(curPos), increment curPos, and return the item.
  165. Black-box checklistCall every operation; test 0, 1, and many items; test boundary and illegal inputs; test cases that should throw.
  166. How do you white-box test expandArray?Fill the array completely so an add forces an expansion.
  167. First step of remove(int pos)Validate that pos is in range; a bad pos is rejected before any shifting.
  168. List vs array: adding at a positionA new list has size 0, so you can't add at pos > size; an array can fill any index immediately.
  169. Linked listA chain of nodes; each node holds data plus a pointer to the next node.
  170. What does the last node's next pointer hold in a singly linked list?null.
  171. Fields of a basic list nodedata and next; next is the same node type, since references are pointers.
  172. 2-arg node constructorSets both data and next.
  173. 1-arg node constructorSets data and sets next to null.
  174. Steps to add a new node after node nCreate the node, point its next at n's next, then point n's next at the new node.
  175. Why must the new node's next be set before n's next when inserting?Otherwise you lose the rest of the list.
  176. One-line insert after node nn.setNext(new Listnode(newdat, n.getNext()))
  177. Cost of adding after a given nodeO(1): one allocation and three field writes, regardless of list size.
  178. What must you find before removing node n?A pointer to the node just before n, by traversing from the head.
  179. Loop to find the node before ntmp = l; while (tmp.getNext() != n) tmp = tmp.getNext();
  180. How do you unlink node n once you have the node before it?tmp.setNext(n.getNext())
  181. Special case when removing the first nodeTest l == n, then set l = n.getNext().
  182. What happens if you skip the first-node special case in remove?The loop runs off the end and you get a null dereference error.
  183. Worst-case cost of removing a node given only a pointer to itO(N), when n is the last node; O(1) if n is first.
  184. Does a removed node still pointing into the list matter?No; it's unreachable from the head.
  185. What is a header node?A dummy node placed before the first real node. You don't store data in it. It lets you add and remove the first node without writing special-case code.
  186. How many nodes does an empty list with a header have?One dummy node.
  187. What position does the header node occupy?Position -1; it is not a data item.
  188. Why must the header be excluded from size and contains?It holds no real data item.
  189. Field holding the header in the linked LinkedList classListnode<E> items
  190. Why keep a lastNode tail pointer?It makes add-at-end O(1) instead of O(N).
  191. What must every modifying method do to lastNode?Keep it current; it equals the header when the list is empty.
  192. Linked list constructor setupitems = lastNode = new header node; numItems = 0.
  193. Add at position pos: which positions are rejected?pos < 0 or pos > numItems, with IndexOutOfBoundsException.
  194. What does add-at-position do when pos == numItems?Delegates to add-at-end, avoiding lastNode fix-up.
  195. How does add-at-position find the insertion point?Walk to the node at pos-1 (header counts as -1), then splice the new node after it.
  196. Cost of removing the first item: linked list vs arrayLinked list O(1); array O(N) because everything shifts left.
  197. Cost of removing the last item: linked list vs arrayLinked list O(N) (traverse to next-to-last); array O(1).
  198. Cost of add-at-end: linked list vs arrayO(1) for both, given a lastNode pointer and amortized array expansion.
  199. Cost of add-at-position: linked list vs arrayO(N) for both; array worst near the front, list worst near the end.
  200. Cost of get: array vs linked listArray O(1); linked list O(N) worst case.
  201. Space overhead of a linked list vs an arrayLinked list adds one pointer per item; an array's capacity can far exceed N after many removes.
  202. Which implementation needs more special cases?The linked version.
  203. Fields of a doubly linked nodeprev, data, next; it has three constructors.
  204. Doubly linked list end pointersFirst node's prev is null; last node's next is null.
  205. Removing node n in a doubly linked listn.getNext().setPrev(n.getPrev()), then n.getPrev().setNext(n.getNext()).
  206. When does doubly linked removal fail with a null dereference?When n is the first or last node; handle with special cases or a circular form.
  207. Trade-off of a doubly linked listExtra pointer per node and more fields to maintain, but O(1) removal given a node and right-to-left traversal.
  208. Circular linked listThe last node's next points to the first node; in the doubly form the first node's prev points to the last.
  209. Why does a naive search on a circular list loop forever?It never hits null when the value is absent; you must stop when you return to the start.
  210. What pointer does a singly circular list keep?A pointer to the last node only.
  211. Costs with a last pointer in a circular listaddFirst, addLast and removeFirst are all O(1).
  212. Circular list addFirst when emptyThe new node points to itself and last = node.
  213. Circular list addFirst when non-emptyNew node points to last.getNext(), then last.setNext(new node).
  214. Circular list addLastCall addFirst, then set last = last.getNext().
  215. Circular list removeFirst when there is one nodeDetect last.getNext() == last, then set last = null.
  216. Circular list removeFirst when non-empty with several nodeslast.setNext(last.getNext().getNext())
  217. Advantage of a circular listFewer special cases, and it fits cyclic models like a network ring.
  218. Primitive type variableHolds the value itself (short, int, long, float, double, boolean, char, byte).
  219. Reference type variableHolds a pointer to an object; new allocates the object (arrays, classes).
  220. Default value of an object field of reference typenull.
  221. AliasingCopying a reference copies the pointer, so two names refer to one object.
  222. Is a mutation through one alias visible through the other?Yes; but reassigning the variable itself is not.
  223. Passing an object to a methodThe parameter aliases the argument; reassigning the parameter inside doesn't affect the caller's variable.
  224. StackAn ordered collection where you can only access the top item; last in, first out.
  225. LIFOLast in, first out — the most recently added item is removed first. That's a stack.
  226. pushAdds an item to the top of a stack.
  227. popRemoves and returns the top item of a stack.
  228. peekReturns the top item of a stack without removing it.
  229. What happens if you pop or peek an empty stack?You get an error (EmptyStackException).
  230. isEmpty (stack)True exactly when the stack's size is 0.
  231. QueueA FIFO collection: add at the rear, remove from the front.
  232. FIFOFirst in, first out — the earliest added item leaves first. That's a queue.
  233. enqueueAdds an item at the rear of a queue.
  234. dequeueRemoves and returns the item at the front of a queue.
  235. What happens if you dequeue an empty queue?You get an error (EmptyQueueException).
  236. Why is a queue more complex than a stack?It's accessed from both ends (front and rear), not just the top.
  237. Why can't Java do new E[n] for a generic array?Generic array creation is forbidden, so you build an Object[] and cast it to E[].
  238. Array stack pop stepsIf empty, throw; else decrement numItems and return items[numItems].
  239. Array stack push stepsIf full, expand; then store at items[numItems] and increment numItems.
  240. Array stack: constructor, isEmpty, pop, peek runtimeO(1) worst and average.
  241. Array stack push runtimeO(1) average, O(N) worst when it must resize and copy.
  242. Linked-list stack pushitems = new ListNode(ob, items); then numItems++.
  243. Linked-list stack runtimesAll operations are O(1) worst case, since there's no resize cost.
  244. Why is the top of an array stack at the end of the array?Adding at the front would be O(N) because of shifting.
  245. Amortized cost of naive array pushO(1) amortized: O(1) normally, O(N) only when the array is full.
  246. Shadow array trickMakes array push always O(1) by avoiding the full-array copy cost.
  247. Linked-list stack pop stepsCheck empty; save data; items = items.getNext(); numItems--; return saved data.
  248. Where is the top of a linked-list stack?At the front of the list, where add and remove are cheapest.
  249. Why is naive array dequeue O(N)?It shifts all remaining elements left to fill the gap.
  250. Circular array queueFront and rear indexes wrap around so freed slots get reused.
  251. incrementIndex in a circular arrayIf index == length−1 return 0, else index+1.
  252. Array queue enqueue stepsExpand if full, advance rearIndex with wrap, store the item, numItems++.
  253. Array queue dequeue stepsAdvance frontIndex with wrap, return the old front value.
  254. Why does plain expandArray fail for a wrapped queue?The wrapped values stay split with a gap instead of becoming contiguous.
  255. Array queue expansion: new sizeDouble the array size.
  256. Array queue expansion: rearIndex after copyingReset rearIndex = frontIndex + numItems − 1.
  257. Linked-list queue: which end is front and rear?Front of the list is the queue front; end of the list is the rear.
  258. Why remove at the front of a linked-list queue?Removing the last node needs its predecessor, which is O(N); front removal is O(1).
  259. Linked-list queue fieldsqFront and qRear pointers plus numItems.
  260. Linked-list queue enqueue/dequeue runtimeO(1) for both.
  261. Linked list vs array space overheadLinked list has one pointer per item; an array can hold far more space than items.
  262. How do you reverse a queue using a stack?Dequeue all into a stack, then pop all back into the queue.
  263. Why does a stack reverse a queue?Stack LIFO flips the queue's FIFO order; it takes O(N) time.
  264. Stack application: method callsRuntime pushes params and locals on call and pops them on return.
  265. Stack application: compilersParsing and syntax checking use a stack.
  266. Stack application: expressionsArithmetic expression evaluation uses a stack.
  267. Queue application: simulationsQueues model waiting lines and event ordering in simulations.
  268. Queue application: graphs and treesSome graph and tree operations use a queue.
  269. What two parts does every recursive method need?A base case (stopping condition) and a recursive call that moves toward it.
  270. What happens if a recursive method has no base case?Infinite recursion, which ends in a StackOverflowError and halts the program.
  271. Why does a guard like if (k == 0) return; fail?It never triggers for negative k, so use k <= 0 to cover negatives.
  272. When does code before the recursive call run?On the way down, before the deeper calls happen.
  273. When does code after the recursive call run?On the way back up, after all deeper calls finish.
  274. In what order do active calls finish?They stack up until the base case, then unwind in reverse order.
  275. Why does recursive factorial(-1) loop forever?The N == 0 base case is never reached, so it recurses endlessly.
  276. Where should you validate negative input for factorial?Once in a wrapper method, then delegate to a helper with no check.
  277. Recursive list sum: base case?node == null returns 0.
  278. Recursive list sum: recursive step?node data + sum(next).
  279. Recursive vowel filter: recursive step?If first char is a vowel keep it, then recurse on the rest; otherwise just recurse.
  280. How do you verify a guessed closed form?Substitute the guess into both sides and simplify to an identity.
  281. Direct vs indirect recursion?Direct: f calls f. Indirect: f calls g and g calls f.
  282. Is recursion usually faster or leaner than iteration?No; it is usually slower and uses more memory, but gives simpler code.
  283. Mental model of a recursive call?Each call clones the code, locals and params; a marker saves the position in each copy.
  284. What happens when a cloned call returns?The clone is discarded and the caller resumes right after its call.
  285. Rule 1 for recursive methods?Every recursive method needs a base case with no recursive call.
  286. Rule 2 for recursive methods?Every call must make progress toward the base case.
  287. What error do you get if either recursion rule is broken?StackOverflowError, and the program halts.
  288. Activation record (AR)One per active method call; holds parameters, local variables and the return address.
  289. What happens on a method call and on return?Call pushes an AR; return pops it and jumps to the saved return address.
  290. Can two calls to the same method return to different places?Yes, because each AR stores its own return address.
  291. Print before the recursive call gives what order?Descending order, like 2 1.
  292. Print after the recursive call gives what order?Ascending order, like 1 2, because it runs during unwinding.
  293. Why choose recursion over iteration?For clarity and faster writing/debugging, not for speed or space.
  294. Factorial definition0! = 1; N! = N × (N−1)! for N > 0; undefined for negatives.
  295. Recursive factorial: base and step?Base N == 0 returns 1; else N * factorial(N−1).
  296. Why does recursive factorial overflow for large N?Each call adds a stack frame, so deep recursion exhausts the stack.
  297. Fibonacci definitionfib(1) = fib(2) = 1; fib(N) = fib(N−1) + fib(N−2) for N > 2.
  298. How does iterative Fibonacci stay fast?It tracks only the two prior values instead of recomputing.
  299. Recursive data structureA structure defined in terms of itself, like a string or linked list.
  300. String as a recursive structure?Either empty, or a char followed by a string.

291 kartu lagi di aplikasi.

Velocer gratis: pengulangan berjarak dan kartu Anda sendiri dari dokumen apa pun.

PDF to flashcards · Lecture to flashcards · Practice exam · Syllabus study plan · Anki import

Dek lain dari University of Wisconsin–Madison