CS50 Fall 2025 - Lecture 1 - C (live, unedited)
Overview
David J. Malan introduces C by translating familiar Scratch ideas into source code, then demonstrates how to compile and run programs in CS50’s VS Code environment. Through examples such as `hello`, `compare`, `agree`, `cat`, and Mario, he teaches C syntax, types, conditionals, loops, functions, scope, and code quality, before showing how integer overflow, truncation, and floating-point imprecision can cause real-world failures.
Key takeaways
- C preserves familiar Scratch concepts such as loops, conditionals, variables, and functions, but requires explicit syntax such as types, braces, semicolons, and function arguments.
- A compiler does more than translate source code into machine code: diagnostics can identify a file, line, and likely mistake, as with a missing semicolon or `stdio.h` declaration.
- Good code has distinct correctness, design, and style dimensions; CS50’s `check50`, `design50`, and `style50` tools target different aspects of that quality.
- C variables have limited scope: a value declared inside a loop or function is unavailable elsewhere unless it is declared in a broader scope or passed as an argument.
- Finite integer ranges can cause concrete failures, including a reported Boeing 787 counter overflow after 248 days and Pac-Man’s corrupted level-256 screen.
- Integer division truncates fractions, and floating-point types approximate many real numbers; choosing an appropriate data type does not remove every representation limit.
Chapters
- The supplied transcript begins at 17:46, so the lecture content before that point is not available here.
- The uploader’s table of contents places the lecture introduction at approximately 17:45.
- David J. Malan connects Scratch concepts such as functions, arguments, variables, loops, and conditionals to C.
- The central shift is from visual puzzle blocks to typed syntax, while the underlying programming ideas remain familiar.
- Source code is the human-readable program; computers ultimately execute machine code represented by zeros and ones.
- A compiler translates C source code into machine code, connecting the programmer’s instructions to the computer’s execution.
- CS50 provides a cloud-based VS Code environment at CS50.dev so students can start without configuring a local machine.
- The editor and file explorer form a graphical user interface, while the terminal is a command-line interface for commands and program execution.
- Syntax highlighting colors recognizable C elements, and keyboard commands become increasingly useful as programming work grows.
- The `code hello.c` command creates a C source file, which Malan fills with `main` and a `printf` call that prints “hello, world.”
- Running `make hello` compiles `hello.c` into an executable named `hello`.
- The command `./hello` runs the executable from the current directory; changing the program name requires updating the related commands.
- C’s `printf` corresponds to Scratch’s output blocks, with parentheses holding the function’s argument and double quotes marking text.
- A semicolon ends a C statement, while braces and indentation organize blocks of code.
- The escape sequence `\n` moves output to a new line; `\"` allows a literal quotation mark inside a quoted string.
- A missing semicolon produces a compiler diagnostic with the filename, line number, and an indication of the expected punctuation.
- Calling `printf` without `#include <stdio.h>` triggers an undeclared-library-function error.
- Header files declare functions from libraries, letting a C program use code written elsewhere.
- CS50’s manual pages at manual.cs50.io provide simplified documentation for C functions such as `printf` and headers such as `stdio.h`.
- Function documentation identifies the relevant header, prototype, behavior, and example code.
- The CS50 library header `cs50.h` provides teaching-oriented input functions such as `get_string`, `get_int`, and `get_char`.
- A string is text, and `get_string("What's your name? ")` prompts for a user’s name and returns it.
- C variables need an explicit type, so the returned text is stored as `string answer`.
- In `printf("hello, %s\n", answer)`, `%s` marks where the string value should be substituted; literal text such as `answer` inside quotes would not access the variable.
- CS50’s cloud programming environment runs on Linux, a Unix-descended operating system widely used for servers and development.
- Commands include `ls` to list files, `mkdir` to create a directory, `rm` to remove files, `mv` to move or rename, `cp` to copy, and `cd` to change directories.
- The terminal’s prompt can show the current directory, and `cd` alone returns to the home directory.
- Malan demonstrates moving `hello.c` into a new `hello` directory with `mkdir` and `mv`, then compiling it from inside that directory.
- The notation `..` means the parent directory, while `.` refers to the current directory.
- The graphical file explorer reflects the same changes made through the command line, and `code filename` opens a chosen file.
- C uses `if`, `else if`, and `else` with a Boolean expression in parentheses and a braced block for each branch.
- A single `=` assigns a value, while `==` tests equality, avoiding confusion between storing a value and comparing two values.
- For values that must be either less than, greater than, or equal, an `else` branch can handle the final case without another comparison.
- C comparison operators include `<`, `>`, `<=`, `>=`, `==`, and `!=`, with `!` indicating negation.
- The `&&` operator combines conditions with logical AND, while `||` combines them with logical OR.
- A character cannot be both lowercase `y` and uppercase `Y`, so accepting either response requires OR rather than AND.
- The lecture introduces `bool`, `char`, `float`, `double`, `int`, and `long` as types for different kinds of values.
- A `float` commonly uses 32 bits and a `double` 64 bits, but neither can represent every real number because both have finite precision.
- For `printf`, `%s` formats strings, `%c` characters, `%f` floating-point values, `%i` integers, and `%li` long integers.
- C variable declarations specify a type, as in `int counter = 0`, before the variable can be used.
- Incrementing can be written as `counter = counter + 1`, `counter += 1`, or `counter++`.
- In `compare.c`, `get_int` obtains values for `x` and `y`, and conditional branches report their relationship.
- A flowchart represents a Boolean test as a decision point and shows how each branch reaches an output or the end of a program.
- Three independent `if` statements can needlessly test every possibility, even after one condition is already true.
- An `if`/`else if` chain avoids redundant checks, and a final `else` can represent the remaining logically certain case.
- The `agree.c` example stores a response from `get_char` in a `char` and compares it with single-quoted character literals.
- Using `||` allows a program to accept either lowercase `y` or uppercase `Y` without duplicating the response code.
- CS50’s `get_char` reprompts when the user enters multiple characters, while an `else` branch can handle responses other than yes.
- A `while` loop repeats its braced code while its Boolean condition remains true.
- A counter starting at 3 can count down with `i--`, or start at 0 and count up with `i++` while `i < 3`.
- A `for` loop combines initialization, condition, and update, making repeated tasks such as printing “meow” three times concise.
- The `cat.c` example first repeats `printf("meow\n")` with a loop instead of copying the same line three times.
- A loop such as `while (true)` deliberately runs indefinitely unless the program exits the loop.
- The lecture demonstrates that an uncontrolled printing loop can overwhelm the VS Code environment and consume substantial CPU.
- Control-C interrupts a running terminal process; Malan uses it to stop the endlessly meowing `cat` program.
- The cat program then uses `get_int` to ask how many times to meow and a `for` loop to repeat that many times.
- CS50’s `get_int` rejects nonnumeric input such as “dog,” but it does not automatically reject negative integers.
- A one-time `if (n < 0)` prompt only offers one retry, while repeating validation code manually creates unnecessary duplication.
- A `while (true)` loop can keep prompting until the input is valid, using `break` to exit and `continue` to start another iteration.
- A variable declared inside a loop’s braces is limited to that scope, so `n` must be declared outside the loop if it is needed afterward.
- A `do while` loop executes its body before testing its condition, making it useful for prompts that must happen at least once.
- The cat input example can request an integer and repeat while `n < 0`, avoiding an initial condition check before the first prompt.
- The Road Runner and Wile E. Coyote comparison illustrates the difference between checking before an action and checking after it.
- A C function can be declared with `void` when it takes no input and returns no value, as in a simple `meow` function.
- Placing the function definition after `main` requires a prototype above `main`, such as `void meow(void);`, so the compiler knows the function exists.
- The `//` syntax starts a comment for human readers, and a parameter such as `int n` lets `meow` repeat a requested number of times.
- A variable declared inside `main` is not automatically visible inside `meow`; the caller must pass its value as an argument.
- The function parameter can use a clearer local name such as `times`, even when the caller passes a variable named `n`.
- Function design distinguishes side effects, such as printing “meow,” from return values that provide reusable data.
- Correctness asks whether code behaves as required, design asks whether its solution is efficient and well structured, and style concerns readability for humans.
- CS50’s `check50` tests correctness against a problem’s expected behavior but does not establish good design or style.
- The CS50 tools `design50` and `style50` provide feedback on program design and consistency with the course style guide.
- Instead of repeating a loop to reject negative values, Malan defines a `get_n` function that returns a nonnegative integer.
- The function uses an integer return type and `return n`, distinguishing its result from a `void` function’s side effect.
- A prototype makes `get_n` available to `main`, where its returned value can be passed directly to `meow`.
- The Mario exercise first prints four question marks directly, then uses a loop to print one character per iteration.
- Putting `\n` inside the loop creates a column; printing the newline after the loop produces a horizontal row.
- Changing the loop output to `#` and including `\n` on each iteration creates a vertical brick column.
- An outer loop handles three rows, and an inner loop prints three bricks across each row to form a 3-by-3 grid.
- The inner loop needs its own counter, so `j` can be used alongside the outer counter `i`.
- Printing a newline after the inner loop, not after every brick, completes each row before the next begins.
- Hard-coding the grid size as `3` in both loop conditions creates duplicated values that must be updated consistently.
- A shared variable such as `n` reduces duplication, and `const int n = 3` further prevents accidental reassignment.
- Named row and column variables can make nested-loop code clearer than generic `i` and `j` counters.
- The calculator uses `get_int` to collect `x` and `y`, then adds them with the `+` operator.
- A temporary variable such as `z` can hold the result, but printing `x + y` directly avoids an unnecessary variable when it is used only once.
- Clear variable names such as `sum` can still improve readability, showing that design choices depend partly on context.
- C uses `*` for multiplication, and the calculator example doubles a dollar amount with `dollars *= 2`.
- Repeated doubling quickly exceeds the range of a typical 32-bit signed integer, producing an incorrect value through integer overflow.
- Changing the variable to `long` and using `%li` increases the available range but does not remove the finite limit.
- A reported Boeing 787 issue involved generator control units entering fail-safe mode after 248 days of continuous power.
- The failure was attributed to an internal software counter overflowing after repeatedly counting tenths of a second.
- The short-term workaround was to power-cycle the aircraft; a software upgrade was developed to address the underlying counter problem.
- Pac-Man’s level counter could reach 255, but advancing to level 256 exposed a missing boundary check.
- The overflow corrupted the display with unexpected characters, turning the bug into a recognizable achievement for skilled players.
- The example shows how a finite integer range can affect a program’s visible behavior, not just its calculations.
- Dividing integers such as `1 / 3` in C produces `0`, because integer division discards the fractional part.
- Changing the inputs to floating-point values and using `%f` allows the calculator to display a decimal approximation.
- The result’s type matters: a decimal-looking answer cannot be preserved if the calculation is performed using integers.
- Formatting a floating-point result with a precision such as `%.50f` can reveal unexpected trailing digits in a calculation like `1 / 3`.
- Finite-bit representations cannot encode every real number, so floating-point calculations approximate many decimal values.
- A `double` offers more precision than a `float`, but neither eliminates approximation for values that cannot be represented exactly.
- The Y2K bug arose because some systems stored years with two digits, making 2000 difficult to distinguish from 1900.
- Systems using a signed 32-bit Unix-time counter risk overflow on January 19, 2038, when counting seconds from January 1, 1970.
- The lecture closes by linking C’s lessons about finite representations to practical software failures and the need to design around data limits.
Transcript excerpt
17:46 All right, this is CS 50, and this is week 1, our second week together, and you'll recall that last week, week zero, we focused on scratch ultimately this graphical programming language by which you can drag and drop puzzle pieces that interlock together only if it makes logical sense to do so. And many of you had actually probably played with that in like middle school or even prior at some point, but for our purposes, the goals of Scratch were to give us sort of a mental model for some fundamental constructs that we're going to see again and again today in C in a few weeks in Python. And even thereafter, and those include things like functions and return variables and arguments and variables and loops and conditionals and more. And so even if today feels like a bit of a fire hose such as that pictured here, appreciate that a lot of today's ideas are exactly the same as last week's ideas. It's just that the syntax is going to change.
18:36 It's going to look a little different. It's going to look a little scarier. It's going to be harder to sort of memorize except with practice will come that muscle memory, but the ideas ultimately are going to be the same. And indeed this is, if unfamiliar, MIT down the road has a tradition of hacks whereby students once a year do something fairly crazy and at this point they happen to connect an actual working uh drinking fountain to an actual fire hydrant, and the sign there very pixelated says Getting an education from MIT is like trying to drink from a fire hose. And that's indeed how computer science, how programming, how CS 50 will sometimes feel, but realize that what's going to be ultimately most important is not where you.
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.