Memory and Pointers
- 53Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
Why is an array a useful way to model computer memory?
Why is an array a useful way to model computer memory?
53 questions
- 1
Why is an array a useful way to model computer memory?
- A
It lets the computer inspect every stored value simultaneously
- B
It guarantees that the values are stored in sorted order
- C
It organizes memory into addressable positions that can hold data
- D
It makes each value accessible without using its position
Correct answer
CIt organizes memory into addressable positions that can hold data
Explanation
Memory can be viewed as bytes arranged in positions, and arrays use indexed positions to organize data. A computer still accesses array elements step by step rather than taking in the entire array at once.
- A
- 2
What is the output of the locker-search problem described in the lecture?
- A
The index of the largest value in the lockers
- B
A sorted copy of all values in the lockers
- C
A Boolean indicating whether the target value is present
- D
The number of lockers examined before stopping
Correct answer
CA Boolean indicating whether the target value is present
Explanation
The search problem asks whether the target number appears among the lockers, so its output is true or false.
- A
- 3
When the values are unsorted and there is no additional information, why might linear search need to inspect every element?
- A
The computer must sort the array before it can compare any values
- B
Linear search checks only the first and last elements, so it must repeat those checks
- C
The target could be the last element or absent, so earlier checks cannot rule out later positions
- D
An array requires every element to be inspected before any comparison is allowed
Correct answer
CThe target could be the last element or absent, so earlier checks cannot rule out later positions
Explanation
In the worst case, the target is at the end or does not occur at all. With no ordering information, each element may need to be checked before concluding whether the target is present.
- A
- 4
What should a linear search return if it reaches the end of the array without finding the target?
- A
True, because the search completed successfully
- B
The index of the final element, because it was checked last
- C
The middle value, because no matching value was found
- D
False, because every element was checked without a match
Correct answer
DFalse, because every element was checked without a match
Explanation
If the loop checks every array element and finds no match, the target is not present, so the Boolean result should be false.
- A
- 5
What condition makes binary search applicable to an array?
- A
The array must contain an even number of elements
- B
The elements must be sorted so comparisons can eliminate one side
- C
The elements must be stored as strings rather than numbers
- D
The target must be larger than the middle element
Correct answer
BThe elements must be sorted so comparisons can eliminate one side
Explanation
Binary search relies on sorted order: comparing the target with the middle element indicates which half could contain it.
- A
- 6
After binary search compares the target with the middle value, how does it choose which half to search?
- A
It always searches the half with more elements
- B
It searches both halves unless the middle value is the target
- C
It searches left if the target is smaller and right if the target is larger
- D
It searches left if the target is larger and right if the target is smaller
Correct answer
CIt searches left if the target is smaller and right if the target is larger
Explanation
In a sorted array, values to the left of the middle are smaller, and values to the right are larger. The comparison therefore identifies which half can contain the target.
- A
- 7
What should a binary search do when the remaining search interval contains no elements?
- A
Continue dividing the empty interval into smaller intervals
- B
Return true because the interval has been fully processed
- C
Return false because no remaining position can contain the target
- D
Restart the search from the beginning of the original array
Correct answer
CReturn false because no remaining position can contain the target
Explanation
An empty search interval means every potentially relevant position has been eliminated without a match, so the target is absent.
- A
- 8
Why can binary search be much faster than linear search on a large sorted array?
- A
It moves the target value to the middle before searching
- B
It checks the array from both ends and meets in the middle
- C
Each comparison can discard about half of the remaining candidates
- D
It compares every value simultaneously using array indexing
Correct answer
CEach comparison can discard about half of the remaining candidates
Explanation
Binary search repeatedly halves the remaining search space, requiring a number of steps that grows logarithmically rather than linearly with the array size.
- A
- 9
What does big O notation describe in the lecture’s treatment of algorithm efficiency?
- A
The lower bound on the running time for the luckiest input
- B
An upper bound on how an algorithm’s running time grows
- C
The amount of memory used, regardless of the algorithm’s steps
- D
The exact number of seconds an algorithm takes on one computer
Correct answer
BAn upper bound on how an algorithm’s running time grows
Explanation
Big O is used as an approximate upper bound on running time, commonly associated with how the algorithm behaves in the worst case.
- A
- 10
Why are O(n) and O(n/2) treated as the same order of growth?
- A
Both expressions describe algorithms that always take exactly n steps
- B
The number of elements is assumed to be two for every input
- C
Big O measures only the best case, where the two costs are equal
- D
Big O ignores constant factors because they matter less as input size grows
Correct answer
DBig O ignores constant factors because they matter less as input size grows
Explanation
Big O focuses on how growth changes with input size and disregards constant multipliers such as dividing the number of steps by two.
- A
- 11
Why can logarithms with different fixed bases be treated as the same order in big O analysis?
- A
A logarithm’s base changes only the algorithm’s best-case time
- B
Big O ignores logarithmic terms altogether
- C
Changing the base changes the logarithm only by a constant factor
- D
Different bases produce identical numerical values for every input
Correct answer
CChanging the base changes the logarithm only by a constant factor
Explanation
Logarithms with different fixed bases differ by a constant multiplier, and big O ignores constant factors.
- A
- 12
What does [0m\Omega notation describe in the lecture’s terminology?
- A
The exact average time across all possible inputs
- B
The number of different values an algorithm can return
- C
A lower bound on an algorithm’s running time
- D
An upper bound on an algorithm’s memory use
Correct answer
CA lower bound on an algorithm’s running time
Explanation
Omega is used to describe a lower bound on running time, often illustrated through an algorithm’s best-case behavior.
- A
- 13
What is the best-case running time of linear search when the target is the first element?
- A
[0m\Omega(1), because one comparison can find it
- B
[0m\Omega(\log n), because the search space is halved
- C
[0m\Omega(n^2), because the array must be repeatedly scanned
- D
[0m\Omega(n), because every element must be compared
Correct answer
A[0m\Omega(1), because one comparison can find it
Explanation
If the target is the first element checked, linear search finds it after one comparison, giving a constant best-case lower bound.
- A
- 14
Why can counting every item in a list have both O(n) and [0m\Omega(n) running time?
- A
Every item must be inspected to produce an accurate count, even in the best case
- B
The count is known from the array’s first value in the worst case
- C
Counting stops as soon as the first item is found, but may inspect all items
- D
The algorithm divides the list in half until the count is determined
Correct answer
AEvery item must be inspected to produce an accurate count, even in the best case
Explanation
An accurate count requires examining all n items regardless of their values, so both the upper and lower bounds are linear.
- A
- 15
Which running-time case does the lecture emphasize more when evaluating an algorithm’s performance?
- A
The worst case, because it describes an upper bound on the work required
- B
The best case, because it describes the most favorable possible input
- C
The case with the smallest input, because it is easiest to measure
- D
The case in which the input is already sorted, regardless of the algorithm
Correct answer
AThe worst case, because it describes an upper bound on the work required
Explanation
The lecture notes that computer scientists typically care more about an algorithm’s upper bound and worst-case performance than about an unusually favorable best case.
- A
- 16
What does [0m\Theta notation indicate in the lecture?
- A
The upper and lower bounds have the same order of growth
- B
The running time is known exactly in seconds
- C
The algorithm uses the same amount of memory for every input
- D
The algorithm’s best case is faster than its worst case
Correct answer
AThe upper and lower bounds have the same order of growth
Explanation
Theta is a shorthand used when an algorithm’s upper and lower bounds are identical in order of growth.
- A
- 17
Why can a better search algorithm fail to make an overall task faster if it requires sorting first?
- A
Binary search requires the array to become unsorted again
- B
Sorting guarantees that the target will be the first value
- C
The cost of sorting may outweigh the time saved by later searches
- D
Sorting makes the values unsuitable for comparison
Correct answer
CThe cost of sorting may outweigh the time saved by later searches
Explanation
Sorting has a cost of its own. Whether sorting followed by faster searches is worthwhile depends on factors such as how often the sorted data will be searched.
- A
- 18
Why should a phone number generally be represented as a string rather than an integer?
- A
It may contain symbols or leading zeros that are meaningful as written
- B
A string automatically sorts phone numbers numerically
- C
It must support arithmetic operations such as addition and multiplication
- D
Integer types cannot store any sequence of decimal digits
Correct answer
AIt may contain symbols or leading zeros that are meaningful as written
Explanation
Phone numbers may include dashes, parentheses, plus signs, or leading zeros. These are formatting characters or meaningful parts of the identifier, not quantities for arithmetic.
- A
- 19
Why does comparing two strings with
==not perform the intended character-by-character equality test in C?- A
A string is represented as an array of characters rather than a single primitive value
- B
C does not allow arrays to contain alphabetic characters
- C
The
==operator compares only the first character of every integer - D
Strings in C are always stored as floating-point values
Correct answer
AA string is represented as an array of characters rather than a single primitive value
Explanation
The lecture explains that a string is an array of characters, so comparing strings requires comparing their contents rather than treating each whole string like a simple scalar value.
- A
- 20
What does the C function
strcmpreturn when its two input strings are identical?- A
One
- B
Zero
- C
A negative number
- D
A positive number
Correct answer
BZero
Explanation
strcmpreturns zero when the strings match; a positive or negative result indicates alphabetical ordering when they differ. - A
- 21
What header is needed to use
strcmpin the program shown?- A
string.h - B
stdio.h - C
cs50.h - D
stdlib.h
Correct answer
Astring.hExplanation
The lecture identifies
string.has the header that declaresstrcmp. - A
- 22
In the phone-book example, why must the program return immediately after printing a matching person’s number?
- A
A successful match requires the program to return a negative value
- B
Returning immediately sorts the names alphabetically
- C
Otherwise, it may continue and execute the final not-found behavior
- D
The number can only be printed after the array is fully scanned
Correct answer
COtherwise, it may continue and execute the final not-found behavior
Explanation
Returning immediately ends the search after a match. If execution instead continues to the end, the program could also print the not-found message despite having found the person.
- A
- 23
In the program convention described, what return value indicates that
maincompleted successfully?- A
-1 - B
The index of the matching array element
- C
1 - D
0
Correct answer
D0Explanation
The lecture presents zero as the conventional successful return value from
main, with one used to indicate failure in the examples. - A
- 24
What design risk arises from storing names and phone numbers in separate arrays at matching indexes?
- A
A phone number at a given index must be a different data type from its name
- B
The arrays can become misaligned, associating a name with the wrong number
- C
The arrays cannot be searched using a loop
- D
The compiler automatically sorts one array but not the other
Correct answer
BThe arrays can become misaligned, associating a name with the wrong number
Explanation
Separate arrays rely on keeping corresponding entries at the same index. Changes such as sorting one array without the other can break that relationship.
- A
- 25
What does a C
structprovide in the person example?- A
A special string type that converts phone numbers into integers
- B
A built-in method for sorting all names alphabetically
- C
A container that groups related fields, such as a name and phone number
- D
A loop that searches multiple arrays at the same time
Correct answer
CA container that groups related fields, such as a name and phone number
Explanation
A structure groups multiple data fields together, allowing a person’s name and phone number to be stored as related information.
- A
- 26
What is the purpose of
typedefin the custom person type example?- A
It defines a type name so the program can declare values of that type
- B
It converts a structure into a sorted array
- C
It automatically fills every structure field with user input
- D
It compares two structures and returns whether they match
Correct answer
AIt defines a type name so the program can declare values of that type
Explanation
The lecture introduces
typedefas a way to define a type, enabling the program to declare an array whose elements are persons. - A
- 27
In an array of
personstructures, what doespeople[i].namerefer to?- A
The number field of the person stored at index
i - B
The
namefield of the person stored at indexi - C
The name of the array’s data type
- D
The
ith character in the name of the first person
Correct answer
BThe
namefield of the person stored at indexiExplanation
The index selects a person in the array, and the dot notation selects that person’s
namefield. - A
- 28
How does grouping a person’s name and number in one structure improve the phone-book design?
- A
It makes the array automatically expand whenever a person is added
- B
It keeps related values together when people are rearranged or sorted
- C
It removes the need to search through the phone book
- D
It ensures that every phone number can be used in arithmetic
Correct answer
BIt keeps related values together when people are rearranged or sorted
Explanation
Keeping related fields together avoids relying on separate arrays remaining in matching order, making it safer to rearrange records.
- A
- 29
What is the central operation of bubble sort?
- A
Divide the array into halves and merge the sorted halves
- B
Repeatedly choose the smallest remaining element and move it into place
- C
Compare neighboring elements and swap them when they are out of order
- D
Compare the target only with the middle element of the array
Correct answer
CCompare neighboring elements and swap them when they are out of order
Explanation
Bubble sort examines adjacent elements and swaps an out-of-order pair. Repeated passes move larger values toward the right.
- A
- 30
Why is bubble sort named for the behavior demonstrated in the lecture?
- A
The array is divided into bubbles that are sorted independently
- B
The algorithm compares each value with every other value simultaneously
- C
The algorithm places the smallest value in the center of the array
- D
Larger values move or “bubble” toward the right side over repeated passes
Correct answer
DLarger values move or “bubble” toward the right side over repeated passes
Explanation
During repeated adjacent comparisons and swaps, larger values gradually move toward their correct positions on the right.
- A
- 31
What is the worst-case running-time order of the basic bubble sort described?
- A
O(logn)
- B
O(n)
- C
O(n2)
- D
O(nlogn)
Correct answer
CO(n2)
Explanation
The described version uses an outer pass and an inner sequence of adjacent comparisons, each on the order of n, leading to O(n2) work.
- A
- 32
Why does the basic bubble sort have a best-case running time of [0m\Omega(n^2) in the lecture’s initial pseudocode?
- A
It performs its prescribed passes even when the input is already sorted
- B
It uses binary search to find every element’s position
- C
It must compare each pair of elements only once
- D
It cannot detect whether two adjacent elements are out of order
Correct answer
AIt performs its prescribed passes even when the input is already sorted
Explanation
The initial pseudocode blindly repeats the passes and does not stop early, so it still performs quadratic work on an already sorted list.
- A
- 33
How can bubble sort improve its best-case running time?
- A
Sort the left half before comparing adjacent elements
- B
Stop when a full pass makes no swaps
- C
Stop after finding the smallest element once
- D
Skip every comparison involving the first element
Correct answer
BStop when a full pass makes no swaps
Explanation
If an entire pass makes no swaps, the list is already sorted. Stopping then allows bubble sort to finish after a single pass in the best case.
- A
- 34
What is the best-case running-time order of bubble sort when it stops after a pass with no swaps?
- A
Ω(n)
- B
Ω(1)
- C
Ω(n2)
- D
Ω(nlogn)
Correct answer
AΩ(n)
Explanation
Even when the input is already sorted, the algorithm must compare neighboring elements in one pass, requiring on the order of n comparisons.
- A
- 35
What is the central operation of selection sort?
- A
Find the smallest remaining element and place it at the next position
- B
Divide the array repeatedly until each part has one element
- C
Search for a target by comparing it with the middle element
- D
Swap every adjacent pair that is out of order
Correct answer
AFind the smallest remaining element and place it at the next position
Explanation
Selection sort repeatedly selects the smallest element from the unsorted portion and places it at the next position in the sorted portion.
- A
- 36
Why does selection sort inspect the entire remaining unsorted portion before selecting its next element?
- A
It has to move every value one position to the left before each selection
- B
It must confirm that the array contains an even number of elements
- C
It needs to compare each value with the first value only
- D
It cannot know which value is smallest without checking the remaining candidates
Correct answer
DIt cannot know which value is smallest without checking the remaining candidates
Explanation
A computer cannot infer that the first value it sees is the smallest; it must inspect all remaining candidates to identify the minimum.
- A
- 37
Why might selection sort swap the smallest value with the value currently occupying its destination rather than shift every intervening value?
- A
A swap guarantees that all remaining values are already sorted
- B
Shifting is not allowed when an array has a fixed size
- C
A swap can place the minimum without moving many other elements individually
- D
Shifting would make the minimum value impossible to compare
Correct answer
CA swap can place the minimum without moving many other elements individually
Explanation
Swapping the minimum with the destination value avoids shifting many elements. The displaced value can be handled during later passes.
- A
- 38
What is the worst-case running-time order of selection sort?
- A
O(nlogn)
- B
O(n)
- C
O(n2)
- D
O(logn)
Correct answer
CO(n2)
Explanation
Selection sort scans the remaining elements repeatedly. The total work is proportional to n+(n−1)+⋯+1, which grows quadratically.
- A
- 39
Why does selection sort still have a quadratic lower bound when the input is already sorted?
- A
It still scans the remaining values to confirm the next smallest element
- B
It is unable to recognize a sorted list because it compares strings
- C
It restarts the algorithm from the beginning after each selection
- D
It must swap every neighboring pair on every pass
Correct answer
AIt still scans the remaining values to confirm the next smallest element
Explanation
Even if the input is already sorted, selection sort still performs its repeated searches for the smallest remaining value, so its work remains quadratic.
- A
- 40
Which distinction between bubble sort and selection sort is accurate?
- A
Bubble sort chooses the next minimum; selection sort repeatedly swaps adjacent pairs
- B
Bubble sort needs sorted input; selection sort works only on unsorted input
- C
Bubble sort divides the list in half; selection sort merges sorted halves
- D
Bubble sort fixes adjacent inversions; selection sort repeatedly chooses the next minimum
Correct answer
DBubble sort fixes adjacent inversions; selection sort repeatedly chooses the next minimum
Explanation
Bubble sort operates on neighboring pairs, while selection sort searches the remaining unsorted portion for its smallest element on each pass.
- A
- 41
What is iteration in programming, as described in the lecture?
- A
Repeating instructions using a loop
- B
Combining two sorted lists into one
- C
Grouping multiple fields into a structure
- D
A function calling itself on a smaller input
Correct answer
ARepeating instructions using a loop
Explanation
Iteration refers to repeating work, commonly by using a loop.
- A
- 42
What makes a function recursive?
- A
It contains two nested loops
- B
It processes an array in alphabetical order
- C
It returns a Boolean value to its caller
- D
It calls itself as part of its own execution
Correct answer
DIt calls itself as part of its own execution
Explanation
A function is recursive when it references and calls itself in its own code.
- A
- 43
Why must a recursive function have a base case?
- A
It ensures that every possible input produces the same result
- B
It makes each recursive call receive a larger problem
- C
It guarantees that the function uses a loop instead of a function call
- D
It provides a stopping condition that prevents endless recursive calls
Correct answer
DIt provides a stopping condition that prevents endless recursive calls
Explanation
A base case identifies a situation that can be handled directly without another recursive call, preventing recursion from continuing indefinitely.
- A
- 44
How does the recursive Mario-pyramid function construct a pyramid of height h?
- A
Print all rows with one nested loop and then call the function again
- B
Print the row of height h first, then draw a pyramid of height h+1
- C
Divide the height into two equal pyramids and merge them
- D
Draw a pyramid of height h−1, then print the additional row
Correct answer
DDraw a pyramid of height h−1, then print the additional row
Explanation
The recursive definition treats a pyramid of height h as a pyramid of height h−1 followed by one additional row of h bricks.
- A
- 45
In the recursive pyramid example, what should happen when the height reaches zero?
- A
Call the function with height negative one
- B
Return without drawing anything
- C
Restart the pyramid at its original height
- D
Print one more row of bricks
Correct answer
BReturn without drawing anything
Explanation
Height zero is the base case: there is nothing to draw, so the function returns rather than calling itself again.
- A
- 46
Why does the recursive pyramid code print the smallest row before the larger rows?
- A
The base case prints the entire pyramid at once
- B
The function sorts the rows by their number of bricks
- C
Recursive calls reach the base case first, then execution returns through earlier calls
- D
The loop always counts down from the original height
Correct answer
CRecursive calls reach the base case first, then execution returns through earlier calls
Explanation
Calls descend to smaller heights until reaching the base case. As those calls return, each earlier call prints its row, producing rows in increasing height.
- A
- 47
What are the three main steps of merge sort for a list with more than one item?
- A
Sort the left half, sort the right half, and merge the sorted halves
- B
Find the minimum, swap it into place, and repeat
- C
Compare adjacent values, swap them, and repeat until no swaps occur
- D
Search the middle, discard one half, and return the target’s index
Correct answer
ASort the left half, sort the right half, and merge the sorted halves
Explanation
Merge sort recursively sorts the two halves and then merges those sorted halves into one sorted list.
- A
- 48
What is the base case for merge sort?
- A
A list with one item is already sorted, so return it
- B
A list with no items must be merged with the original list
- C
A list that contains the largest possible value must be returned
- D
A list with two items is always already sorted
Correct answer
AA list with one item is already sorted, so return it
Explanation
A one-item list is sorted by definition, so merge sort can return it without doing further work.
- A
- 49
When merging two sorted lists, which value should be placed next in the output?
- A
The value that appeared first in the original input
- B
The middle value of the original unsorted list
- C
The smaller of the first unmerged values in the two lists
- D
The larger of the last values in the two lists
Correct answer
CThe smaller of the first unmerged values in the two lists
Explanation
Because both input lists are sorted, their first unmerged values are their respective smallest remaining values. Choosing the smaller one maintains sorted order.
- A
- 50
Why does merge sort require additional space in the merge step described?
- A
It converts each number into a string before comparing it
- B
It stores a separate copy of every recursive function call as an array
- C
It needs room to combine elements from the two sorted halves in order
- D
It must preserve the original unsorted list while searching for a target
Correct answer
CIt needs room to combine elements from the two sorted halves in order
Explanation
The example uses extra space to place elements from the two sorted halves into their correctly merged order.
- A
- 51
Why does merge sort have running time O(nlogn) in the lecture’s analysis?
- A
It scans all n elements once and then performs n2 swaps
- B
Each of about logn levels processes all n elements during merging
- C
It compares only logn elements and makes n recursive calls
- D
It divides the list into n parts and merges them in constant time
Correct answer
BEach of about logn levels processes all n elements during merging
Explanation
The list can be divided in half for about logn levels. At each level, merging processes a total of about n elements, yielding nlogn work.
- A
- 52
What is the best-case running-time order of the merge sort described, even if its input is already sorted?
- A
Ω(nlogn)
- B
Ω(n)
- C
Ω(1)
- D
Ω(n2)
Correct answer
AΩ(nlogn)
Explanation
The described merge sort does not stop early for already sorted input; it still divides the list and merges at each level, so its best-case order is nlogn.
- A
- 53
How can the running-time bounds of merge sort be summarized using theta notation?
- A
Θ(n2), because every sorting algorithm compares every pair
- B
Θ(nlogn), because its upper and lower bounds have the same order
- C
Θ(n), because each merge processes the list once
- D
Θ(logn), because the list is repeatedly divided in half
Correct answer
BΘ(nlogn), because its upper and lower bounds have the same order
Explanation
The lecture gives merge sort both an O(nlogn) upper bound and an Ω(nlogn) lower bound, allowing the concise description Θ(nlogn).
- A

Ask anything
We've read this whole study set, so questions about it get the best answers.