CS50 Fall 2025 - Lecture 2 - Arrays (live, unedited)
Overview
David Malan uses C examples to show how debugging tools and an understanding of memory help programmers move from working code to better-designed code. The lecture explains compiler stages, arrays as contiguous memory, strings as null-terminated character arrays, and command-line arguments and exit statuses, then applies those ideas to reading levels and Caesar-cipher encryption.
Key takeaways
- C arrays provide one contiguous block of same-type values, but the programmer must track the array's length separately when passing it to a function.
- A C string is a character array terminated by '\0'; a visible three-character string therefore occupies at least four bytes.
- Debugging is more effective when tools expose program state: temporary printf statements reveal values, while debug50 breakpoints allow line-by-line inspection.
- C compilation comprises preprocessing, compiling to assembly, assembling to machine code, and linking library implementations into an executable.
- Integer division truncates fractional results; an average needs floating-point arithmetic, such as dividing by 3.0 or casting an operand.
- Command-line programs use argc and argv to receive arguments, and main's return value communicates success or failure through an exit status.
Chapters
- The supplied transcript begins at 23:19, so the lecture's first 23 minutes cannot be summarized reliably from this text.
- The uploader's table of contents places the Reading Levels segment at approximately 23:16.
- Leah reads a short Dr. Seuss passage, which the audience estimates at kindergarten level and a formula later rates below grade 1.
- Maria reads a rhyming passage rated at grade 3, while Omar's excerpt from 1984 is rated at grade 10.
- Calculating a reading level requires representing and analyzing a body of text, motivating closer work with strings.
- Cryptography aims to scramble a message reversibly so a recipient can decrypt it even if others intercept it.
- David Malan previews an encrypted message that resolves to “This is CS50” and frames secure communication as a course problem.
- Debugging tools should help students locate bugs themselves rather than depend on a TA or the CS50 virtual duck.
- Grace Hopper, a U.S. Navy rear admiral and early Harvard Mark I programmer, is associated with popularizing the term “bug.”
- A moth found in the Harvard Mark II circuitry was logged as the “first actual case of bug being found.”
- The anecdote introduces debugging as finding and removing mistakes in software.
- The deliberately broken buggy.c program first omits stdio.h, which declares printf, and then omits a semicolon.
- Compiler messages identify the file and line, such as buggy.c:3, and point toward the missing declaration or syntax.
- The correct header is stdio.h, not the commonly mistyped studio.h.
- C requires a variable declaration such as string name, unlike languages that infer or omit types in similar situations.
- string and get_string are provided by the CS50 library, so the program must include cs50.h.
- A program can compile yet behave incorrectly: printing “hello” instead of “hello David” is a logic bug fixed with %s and name.
- A loop initialized at i = 0 and conditioned on i <= 3 prints four bricks, not the intended three.
- Temporary printf output reveals the loop values 0, 1, 2, and 3, making the extra iteration visible.
- Changing the condition to i < 3 fixes the bug while preserving the conventional zero-based loop.
- The pyramid example moves brick printing into a helper function, print_column, which accepts a height.
- C requires a function prototype above main if the function implementation appears later in the file.
- The prototype communicates the function name, parameter type, and return type before the compiler encounters a call.
- Running debug50 buggy launches a debugger that can pause execution and advance through code one line at a time.
- A breakpoint, set by clicking beside a line number in VS Code, tells the debugger where to pause.
- At a breakpoint, the debugger displays local variables and the call stack alongside the highlighted source line.
- Step over executes the current line; step into follows a function call, allowing inspection inside print_column.
- The debugger shows i progressing through 0, 1, 2, and 3 while the program prints four hashes for a requested height of 3.
- The visible value i = 3 confirms that the condition i <= height admits the unwanted fourth iteration.
- A breakpoint can be placed directly inside print_column if main does not need to be inspected first.
- Uninitialized variables may display garbage values, such as the debugger's example value for h before user input.
- A for loop initializes once, checks its Boolean condition, executes its body, updates, and checks again.
- The compiler translates C source code into machine instructions represented by zeros and ones.
- make is a convenience command, not the compiler itself; the C compiler used in the demonstration is Clang.
- Understanding the stages beneath make helps explain compiler and linker error messages.
- Running clang hello.c produces an executable named a.out by default.
- The executable runs as ./a.out, while make hello conveniently creates an executable named hello.
- The make command avoids requiring beginners to memorize compiler options and default filenames.
- A program using get_string may fail with an undefined reference if Clang is not told to link the CS50 library.
- The command clang hello.c -lcs50 links the library implementation to the program.
- The -o hello option names the output executable, combining with -lcs50 to make a direct Clang command more explicit.
- Compilation is a common umbrella term for four processes: preprocessing, compiling, assembling, and linking.
- During preprocessing, directives such as #include cause header-file contents to be incorporated into the source.
- Headers provide function prototypes, including declarations for printf in stdio.h and get_string in cs50.h.
- The compiler converts preprocessed C into assembly instructions for a CPU architecture.
- The assembler turns those instructions into machine-code bits, and the linker combines a program's code with library code.
- The -lcs50 option resolves the library implementation needed for functions such as get_string.
- The same C source can produce different assembly instructions for different CPUs, such as those in phones and PCs.
- Separate compiler stages let different tools and teams handle preprocessing, compilation, assembling, and linking.
- The machine's bit patterns follow conventions that distinguish instructions and data, a topic revisited later in the course.
- A compiled executable can be inspected, but translating its zeros and ones back into readable source is painstaking.
- Equivalent source constructs, such as a for loop and a while loop, may produce functionally equivalent machine code, obscuring the original choice.
- JavaScript differs because its source code is commonly delivered to browsers and can be inspected directly.
- The class pauses for a 10-minute break at about 85:51.
- The lecture resumes at about 96:50 with a discussion of C data types and the memory they occupy.
- The examples assign typical sizes of 1 byte to bool and char, 4 bytes to int and float, and 8 bytes to long and double.
- A string's storage depends on its character count, unlike fixed-size numeric types.
- A computer's memory can be pictured as addressed bytes, with multi-byte values stored in contiguous locations.
- The scores.c example averages three problem-set scores: 72, 73, and 33.
- Integer division computes 178 / 3 as 59, discarding the fractional part rather than displaying 59.333.
- Changing the printf format to %f alone causes a type mismatch because the calculated expression is still an integer.
- Using 3.0 in the denominator promotes the arithmetic to floating point and restores the fractional score.
- A cast such as (float) length is another way to request floating-point division, though floating-point imprecision remains.
- Each int score occupies a typical 4 bytes, so three independently declared scores use 12 bytes.
- Three separately named score variables do not scale well when a program must store dozens or hundreds of scores.
- An array reserves one contiguous block of memory for a specified number of values of the same type.
- The declaration int scores[3] creates space for three integers under one array name.
- Array elements are accessed with zero-based indices: scores[0], scores[1], and scores[2].
- A for loop can prompt for each of three scores using scores[i] = get_int(...), replacing repeated input statements.
- A named constant such as const int N = 3 avoids repeating a magic number for array size and loop bounds.
- The average function accumulates values with sum += numbers[i] and divides the total by the number of elements.
- In C, the function must receive the array and its length separately, for example numbers[] and length.
- Returning sum / length as integer arithmetic repeats the truncation bug; converting the sum or length enables a fractional result.
- The char variables 'H', 'I', and '!' print as text with %c and as the numbers 72, 73, and 33 with %i.
- These values correspond to ASCII character codes, so a character can also participate in numeric operations.
- Single quotes denote character constants, while double quotes denote strings.
- A string such as "HI!" occupies successive character locations and can be indexed as s[0], s[1], and s[2].
- Printing those positions with %c reproduces the text, while printing them with %i reveals ASCII values.
- For the lecture's examples, a string is understood as an array of characters rather than an indivisible value.
- C appends the null character, written '\0', after a string's visible characters.
- A three-character string such as "HI!" therefore requires four bytes, including its terminating null byte.
- Functions such as printf can stop reading a string when they encounter this zero-valued character.
- Two strings such as "HI!" and "BYE!" each occupy character sequences terminated by '\0'.
- An array can hold strings, as in string words[2], with words[0] and words[1] selecting the individual strings.
- Nested indexing such as words[1][2] selects a character from a string inside the array.
- A manual string-length loop advances through name[n] until it finds '\0', counting visible characters but not the terminator.
- The example counts David and Kelly as five characters each, and an empty input as zero characters.
- The manual loop demonstrates the representation but need not be rewritten in every program.
- The standard string.h library provides strlen, which returns a string's length without a custom counting loop.
- Calling strlen(s) in a loop condition recomputes the same length on every iteration when the string is unchanged.
- Storing the result in n once, including in a for-loop initializer, avoids repeated calls and illustrates a general optimization principle.
- Because lowercase ASCII letters follow uppercase letters by 32, subtracting 32 from a lowercase character produces its uppercase counterpart.
- The ctype.h functions islower and toupper replace manual character-range checks and arithmetic.
- The compact approach prints toupper(s[i]) for each character, leaving already-uppercase letters unchanged.
- C's main can take int argc and string argv[] instead of void when a program needs command-line arguments.
- argv[0] contains the program name; argv[1] contains the first argument supplied by the user.
- argc counts all command-line words, including the program name, so a program name plus one user argument gives argc == 2.
- By convention, main returns 0 for success and a nonzero value, such as 1, to indicate an error.
- After running a program, echo $? reveals its exit status; CS50's check50 can use that status when assessing execution.
- The cowsay command demonstrates arguments that change output, such as a message or an animal selected with an option like -f duck.
- A Caesar cipher shifts letters by a secret key; with key 1, H becomes I and I becomes J, while punctuation remains unchanged in the example.
- Decryption reverses the shift, and ROT13 uses a 13-letter rotation to obscure text without providing strong security.
- An attacker can try the 25 nontrivial letter shifts, making simple Caesar encryption vulnerable to brute force.
Transcript excerpt
23:19 1 fish, 2 fish, red fish, blue fish. Congratulations. Today is your day. You're off to great places. You're off and away. It was a bright cold day in April, and the clocks were striking 13. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of victory mansions, though not quickly enough to prevent a swirl of gray dust from entering along with him. All right. This is CS 50, and this is week 2, and if we could after this dramatic reading, a round of applause for our volunteer. So we can now take for granted from week one that we now have a new way to express some
24:09 of the ideas that we first explored in week 0 like functions and conditionals and variables and the like, and now we're doing in see what we used to do in scratch. Today what we're going to start to focus on is some real world problems so that we can take for granted that we have that expressiveness. We have some tools in our toolkit and actually start to solve some real world problems. Problems if representative thereof. In particular, the real world problem that we're going to start today and this week with is that of reading levels. Odds are when growing up you read at a certain level based on the age at which you were at. Maybe it was 1st grade level or 5th grade level or 10th grade level or the like, and that was a function of just how comfortable you were with the words in the book or words on the screen that you were reading. What you've just Thanks to our volunteers are 3 different reading levels that each of these 3 volunteers reads at.
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, CS50.