Docsity

CS50 Algorithms, C & Python Programming Exam Prep 2026–2027, Exams of Programming Languages

Partial preview of the text

Download CS50 Algorithms, C & Python Programming Exam Prep 2026–2027 and more Exams Programming Languages in PDF only on Docsity!

CS 50 Harvard Introduction to Computer Science Comprehensive Core

Exam Prep 120+ Algorithm and C Python Programming Solved Questions

CS50: Introduction to Computer Science Prep with Detailed Rationales Course Code: CS Course Name: Introduction to Computer Science Topic: Algorithms, C, and Python Programming Academic Year: 2026/

Question 1 In C programming, which data type should be used to store a single 8-bit character code under the ASCII standard? A) int B) char C) float D) double CORRECT ANSWER: B) char RATIONALE: In C, the char data type is specifically designed to store 8-bit single- byte values, which maps directly to standard ASCII character codes (values ranging from 0 to 255 or - 128 to 127). An int typically occupies 4 bytes (32 bits), while float and double represent single-precision and double-precision IEEE 754 floating-point numbers respectively.

Question 2 What is the primary function of the compiler (such as clang or gcc) in the context of C programming? A) Executing code line-by-line at runtime B) Translating source code into low-level machine code object files C) Automatically fixing logical and structural syntax errors in code D) Allocating memory dynamically on the heap during execution CORRECT ANSWER: B) Translating source code into low-level machine code object files RATIONALE: A compiler converts high-level C human-readable source code into binary machine code (executable instructions composed of 0s and 1s) prior to execution. Line-by-line execution is the characteristic of an interpreter (e.g., standard Python). Compilers report syntax errors but cannot fix them automatically, and dynamic heap allocation occurs at runtime via functions like malloc().

Question 3 Consider the following C code snippet:

**Question 5** What is the exact outcome of evaluating the expression `!(5 > 3 && 2 == 4)` in C boolean logic? A) **0 (false)** B) **1 (true)** C) Syntax Error D) Undefined Behavior *CORRECT ANSWER:* B) **1 (true)** *RATIONALE:* Evaluating inner expressions: `(5 > 3)` is `1` (true). `(2 == 4)` is `0` (false). The conjunction `1 && 0` evaluates to `0` (false). Applying the logical NOT operator `!` to `0` yields **1 (true)**. --- **Question 6** Which condition describes an **infinite loop** in C construct logic? A) A loop whose condition evaluation always returns non-zero ( **true** ) B) A loop that executes exactly $N$ times where $N = 2^{31}-1$ C) A loop missing explicit type conversion on its counter D) A loop using `break` statements inside nested conditionals *CORRECT ANSWER:* A) A loop whose condition evaluation always returns non- zero ( **true** ) *RATIONALE:* In C, non-zero values represent **true** , while zero represents **false**. If a loop conditional statement (e.g., `while (1)`) remains permanently non-zero without internal terminating directives (`break`, `return`), the loop never satisfies its termination criteria, causing an **infinite loop**. --- **Question 7** In CS50's `cs50.h` library, which function is used to safely request a single **string input** from the user at command-line runtime? A) `scanf()` B) `get_string()` C) `readline()` D) `input_string()` *CORRECT ANSWER:* B) `get_string()` *RATIONALE:* The **`get_string()`** abstraction in `cs50.h` automatically manages dynamic memory allocation and buffer management when prompting users for string inputs, preventing common standard `scanf()` vulnerabilities like buffer overflows. --- **Question 8** What is the index of the **first element** in any standard array initialized in C? A) - 1 B) 1 C) 0 D) Variable based on initial declaration size *CORRECT ANSWER:* C) 0 *RATIONALE:* C uses **zero-based indexing** for arrays. The index specifies the offset from the array's base memory address; thus, the initial element resides at an offset of 0 bytes times element size, corresponding to index `0`. --- **Question 9** In C programming, what character acts as the universal **null terminator** for null- terminated strings? A) `'\n'` B) `'\t'` C) `'\0'` D) `'NULL'` *CORRECT ANSWER:* C) `'\0'` *RATIONALE:* Strings in C are arrays of characters ending with the **null terminator** `'\0'` (ASCII byte value 0). This signals to standard library functions like `strlen()` or `printf()` where string content terminates in continuous memory blocks. B) **Selection Sort** C) **Bubble Sort** D) **Insertion Sort** *CORRECT ANSWER:* C) **Bubble Sort** *RATIONALE:* **Bubble Sort** iterates through an array repeatedly, checking neighbor pairs (`arr[i]` and `arr[i+1]`) and swapping them if out of order, causing larger unsorted values to "bubble" up to the array tail on each pass. --- **Question 13** What is the worst-case **Big O time complexity** for searching an item across an unsorted list of $N$ items using **Linear Search**? A) $O(1)$ B) $O(\log N)$ C) $O(N)$ D) $O(N^2)$ *CORRECT ANSWER:* C) $O(N)$ *RATIONALE:* In **Linear Search** , if the target element is located at the terminal position or does not exist, every element among $N$ total elements must be checked sequentially, producing an $O(N)$ linear worst-case time bound. --- **Question 14** What primary prerequisite must be met prior to invoking a **Binary Search** algorithm over a array dataset? A) The array must be stored entirely on the heap B) The array elements must be **sorted** in sequential order C) The size of the array must be an even number D) The array cannot contain duplicate numerical values *CORRECT ANSWER:* B) The array elements must be **sorted** in sequential order *RATIONALE:* **Binary Search** divides the search space in half by comparing the target with the median element. This logic relies entirely on the array being **sorted** ; without order, discarding half the search window could eliminate the target element. --- **Question 15** What is the worst-case time complexity of **Binary Search** operating over an array of size $N$? A) $O(N)$ B) $O(N \log N)$ C) $O(\log N)$ D) $O(1)$ *CORRECT ANSWER:* C) $O(\log N)$ *RATIONALE:* Because **Binary Search** cuts the remaining sub-array elements in half ($N/2, N/4, N/8...$) with each comparison step, the maximum number of comparative iterations required scales logarithmically as $O(\log_2 N)$, simplified in Big O as $O(\log N)$. --- **Question 16** What structural concept allows a function in C or Python to call **itself** internally to solve smaller sub-problems? A) Iteration B) **Recursion** C) Dynamic Allocation D) Encapsulation *CORRECT ANSWER:* B) **Recursion** *RATIONALE:* **Recursion** occurs when a function invokes itself directly or indirectly. A recursive routine relies on a **base case** to halt self-invocations and a **recursive case** that reduces the problem towards the base case condition. --- ## C) $O(N)$ D) $O(\log N)$ *CORRECT ANSWER:* B) $O(N \log N)$ *RATIONALE:* **Merge Sort** divides array inputs in half recursively down $\log_2 N$ levels of recursion tree depth, performing $O(N)$ linear comparison and copy work across each level to re-merge lists, leading to a constant worst-case complexity of $O(N \log N)$. --- **Question 20** Which algorithm choice exhibits a best-case time complexity of $\Omega(N)$ when optimizing with an early-exit check for already sorted input? A) Standard Selection Sort B) Optimized **Bubble Sort** C) Merge Sort D) Unsorted Linear Search *CORRECT ANSWER:* B) Optimized **Bubble Sort** *RATIONALE:* An optimized **Bubble Sort** keeps a boolean flag checking whether any swaps occurred during a full pass over $N$ items. If zero swaps occur on pass 1, the algorithm breaks early, completing in linear $\Omega(N)$ best-case runtime complexity. --- **Question 21** In C, what is the fundamental definition of a **pointer** variable? A) A special structure storing large file buffers B) A variable that stores the **memory address** of another variable C) An array that dynamically changes its allocation size automatically D) A built-in function to reference dynamic objects in RAM *CORRECT ANSWER:* B) A variable that stores the **memory address** of another variable *RATIONALE:* A **pointer** is a variable whose explicit value is the hex address of a specific region in memory (RAM) allocated to another piece of data or structure. --- **Question 22** Which operator is used in C to extract the exact **memory address** of an existing variable? A) Dereference operator `*` B) Address-of operator `&` C) Arrow operator `->` D) Dot operator `.` *CORRECT ANSWER:* B) Address-of operator `&` *RATIONALE:* The **`&` (address-of) operator** returns the numerical memory address where a variable resides. Conversely, `*` (dereference operator) retrieves or alters contents residing *at* a pointed address. --- **Question 23** What happens when you dereference a **NULL pointer** in C (e.g., `int *p = NULL; *p = 10;`)? A) The variable `p` is assigned value `0` B) The compiler automatically reassigns `p` to stack memory C) A runtime **segmentation fault** occurs due to invalid memory access D) The execution completes with status code `1` silently *CORRECT ANSWER:* C) A runtime **segmentation fault** occurs due to invalid memory access *RATIONALE:* A **NULL pointer** points to address zero, an invalid user memory location reserved by operating systems. Dereferencing NULL causes an illegal memory access trap resulting in a fatal program halt called a **segmentation fault**. --- **Question 24** Which standard library function is responsible for dynamically allocating contiguous blocks of memory from the **heap** in C? *RATIONALE:* **Valgrind** (specifically its `memcheck` tool) monitors binary execution step-by-step to detect memory vulnerabilities including unfreed heap pointers (leaks), invalid reads/writes, out-of-bounds accesses, and use-after-free conditions. --- **Question 27** In standard C memory layout models, which segment holds local variables declared inside active function calls? A) Heap B) **Stack** C) Text / Code D) Data *CORRECT ANSWER:* B) **Stack** *RATIONALE:* Local variables, function frame variables, and return parameters are automatically allocated in contiguous memory frames on the **stack** , which grows downward in RAM during function calls and shrinks as functions return. --- --- **Question 28** How do the **Stack** and the **Heap** differ in terms of growth direction and allocation management in C? A) Stack grows downward and manages automatic local variables; Heap grows upward and manages dynamic explicit allocations. B) Heap grows downward and manages function frames; Stack grows upward for `malloc()`. C) Both grow downward from the exact same memory pointer location. D) Stack is stored on disk; Heap is stored in physical RAM. *CORRECT ANSWER:* A) Stack grows downward and manages automatic local variables; Heap grows upward and manages dynamic explicit allocations. *RATIONALE:* Memory models layout local variables on the **stack** (growing top- down), managed automatically by scope entry/exit. Dynamic allocations (`malloc`) occupy the **heap** (growing bottom-up), manually allocated and freed by the developer. **Question 29** Given a pointer to a struct `node *n`, which syntax choice correctly accesses its internal field `number`? A) `n.number` B) `*n.number` C) `n->number` D) `&n->number` *CORRECT ANSWER:* C) `n->number` *RATIONALE:* The arrow operator **`->`** dereferences a structure pointer and accesses a internal struct field in a single operation (`n->number` is functional shorthand equivalent to syntactic expression `(*n).number`). --- **Question 30** What vulnerability happens when writing more data to an array buffer than allocated, potentially overwriting adjacent memory addresses? A) **Buffer Overflow** B) Memory Leak C) Dynamic Instantiation D) Garbage Collection *CORRECT ANSWER:* A) **Buffer Overflow** *RATIONALE:* A **buffer overflow** happens when data written to a contiguous sequence of memory bounds exceeds capacity, spilling into and corrupting neighboring stack or heap contents. This creates severe system safety and cyber security risks. --- **Question 31** What does the string comparison function `strcmp(s1, s2)` return when both string sequences `s1` and `s2` contain **identical** characters? A) `1` B) **`0`** itself; `ptr` retains the old address as a dangling pointer unless explicitly reassigned to `NULL`. --- **Question 34** What is the structural memory layout of a basic **singly linked list** node in C? A) An array storing values alongside a global size variable B) A `struct` containing a data value field and a **pointer** to the next node C) A double array holding keys and index positions D) A continuous block of memory allocated in a single `malloc` call *CORRECT ANSWER:* B) A `struct` containing a data value field and a **pointer** to the next node *RATIONALE:* A **singly linked list** consists of heap-allocated structure nodes, where each node encapsulates actual data elements along with a pointer variable (`next`) referencing the address of the subsequent node in sequence. --- --- **Question 35** What is the worst-case time complexity required to locate a specific element inside a **singly linked list** containing $N$ nodes? A) $O(1)$ B) $O(\log N)$ C) $O(N)$ D) $O(N^2)$ *CORRECT ANSWER:* C) $O(N)$ *RATIONALE:* Unlike contiguous arrays offering constant-time $O(1)$ index lookup, linked lists require **linear traversal** pointer-by-pointer starting from `head` through up to $N$ connected nodes, yielding an $O(N)$ worst-case time bound. --- **Question 36** Inserting a new item at the absolute **beginning (head)** of an existing singly linked list runs in what time complexity? A) $O(1)$ B) $O(N)$ C) $O(\log N)$ D) $O(N^2)$ *CORRECT ANSWER:* A) $O(1)$ *RATIONALE:* Prepending a node requires setting the new node's `next` pointer to the current `head` and reassigning the `head` pointer to the new node. This takes constant time $O(1)$ regardless of list size $N$. --- **Question 37** How does a **doubly linked list** structural node differ fundamentally from a singly linked list node? A) It contains two distinct data values instead of one B) It maintains pointers to **both** the next node and the **previous node** C) It stores data items on both the stack and heap simultaneously D) It converts linear runtime complexity to logarithmic runtime *CORRECT ANSWER:* B) It maintains pointers to **both** the next node and the **previous node** *RATIONALE:* A **doubly linked list** node encapsulates two pointers: a `next` pointer referencing the succeeding node and a `prev` pointer referencing the preceding node. This allows bidirectional traversal across the sequence. --- **Question 38** In computer science data structures, what is a primary structural advantage of a **Hash Table** over a raw unsorted list? A) Guarantees sorted data retrieval at all times B) Uses less memory footprint than simple arrays *RATIONALE:* **Separate Chaining** structures each element of the hash table's array as a pointer to the head of a linked list. When multiple keys hash to the same bucket index, new values are inserted as additional nodes along that bucket's linked list chain. --- **Question 41** What is the absolute **worst-case time complexity** for searching an item in a Hash Table with $N$ total elements if all keys collide into a single bucket chain? A) $O(1)$ B) $O(\log N)$ C) $O(N)$ D) $O(N^2)$ *CORRECT ANSWER:* C) $O(N)$ *RATIONALE:* If a poorly optimized hash function assigns all $N$ elements to the exact same array index, the hash table degrades into a standard singly linked list, turning lookups into sequential $O(N)$ linear searches. --- **Question 42** What is a **Trie** (prefix tree) data structure primarily optimized for in terms of search operations? A) Mathematical sorting of real numbers B) Fast prefix matching and lookup of **string keys** proportional to key length C) Dynamic memory stack allocation reduction D) Direct hardware cache optimization *CORRECT ANSWER:* B) Fast prefix matching and lookup of **string keys** proportional to key length *RATIONALE:* A **Trie** is a tree structure where each node represents a character mapping of a string key. Lookups execute in $O(k)$ time, where $k$ is string length, independent of total stored items $N$. --- **Question 43** What is the worst-case time complexity to search for a word of length $k$ inside a Trie containing $N$ total stored words? A) $O(N)$ B) $O(k)$ C) $O(N \log k)$ D) $O(k^2)$ *CORRECT ANSWER:* B) $O(k)$ *RATIONALE:* Searching in a Trie involves traversing down tree branches character by character across the input word length $k$. Because each step evaluates one letter, execution depends strictly on length $k$, evaluating to $O(k)$ time irrespective of total word count $N$. --- **Question 44** In a **Binary Search Tree (BST)** , which constraint must hold true for every valid internal node $X$? A) Nodes in the left subtree must be $\le X$, and nodes in the right subtree must be $\ge X$ B) Left subtree nodes must be greater than $X$, and right subtree nodes must be smaller C) Every node must maintain exactly two child pointers that are non-null D) Parent node values must be equal to the sum of child node values *CORRECT ANSWER:* A) Nodes in the left subtree must be $\le X$, and nodes in the right subtree must be $\ge X$ *RATIONALE:* The **Binary Search Tree invariant** dictates that for any node $X$, all key values stored within its left subtree must be strictly less than or equal to $X$, while all key values stored within its right subtree must be strictly greater than or equal to $X$. --- **Question 45** What is the worst-case search runtime complexity in a **Binary Search Tree** containing $N$ elements that has degraded into an unbalanced linear sequence?