- Model computing problems as inputs transformed into outputs.
- Explain how binary patterns can encode numbers, text, color, audio, video, instructions, and memory addresses.
- Describe algorithms using pseudocode and compare their correctness and running time with Big O notation.
- Recognize functions, conditionals, Boolean expressions, loops, variables, data types, pointers, arrays, and other data structures.
- Explain how editors, terminals, compilers, and build utilities support programming.
- Identify the roles of HTML, CSS, JavaScript, HTTP, Flask, SQL, and abstraction in web applications.
Foundations of Computer Science and Programming
Computer science develops precise, algorithmic ways to transform information and solve problems.
Computer science is fundamentally a discipline of problem-solving. A useful mental model begins with some input, applies a process, and produces an output. Programming gives a computer the instructions needed to carry out that process.
For a program that adds two integers, identify its input, its operation, and its output.
The two integers are the input, addition is the operation, and their sum is the output.
Binary and the Representation of Information
A computer assigns meaning to patterns of bits according to their context, data type, standard, or file format.
Binary and Number Systems
At the machine level, computers work with patterns of0and1. With three bits, for example, zero can be written as000and one as001. Each added bit increases the set of patterns available for representing information.
| System | Base | Symbols and use |
|---|---|---|
| Decimal | 10 | The familiar human notation using digits 0 through 9. |
| Binary | 2 | Uses only 0 and 1 to encode computer data and instructions. |
| Hexadecimal | 16 | Continues from 0–9 through A–F; one hexadecimal digit represents four bits. |
Letters and Characters
Character standards associate numbers with written characters. In ASCII, for instance,Hmaps to decimal72,Ito73, and!to33. Devices interpret the corresponding bit patterns by following that shared mapping.
ASCII could not cover all written languages and symbols. Unicode extends it with many more numerical mappings and may use 8, 16, or 32 bits. This larger standard can represent writing systems, punctuation, and emojis.
Context and File Formats
A bit pattern has no single meaning by itself. Its interpretation depends on context: the same bits might be treated as a number, text, a color, or a machine instruction. Programs and declared data types provide that context.
- A JPEG content type tells software to interpret the data as an image.
- An MP4 identifies multimedia data that can contain video and audio.
- The
.docxextension identifies a Microsoft Word document rather than source code.
Large multimedia formats use containers, codecs, and compression to encode information with fewer bits. Lossless compression preserves all information, while lossy compression does not.
Color, Video, and Audio
RGB represents a color by assigning separate numerical amounts of red, green, and blue. Each amount can range from0to255, and their combination determines the displayed color.
- Video can be understood as a sequence of images, each built from pixels whose colors are encoded with bits.
- Audio can be encoded numerically. MIDI, for example, can represent notes along with properties such as duration and volume.
Algorithms and Efficiency
An algorithm must produce the right result, and its resource use matters as the input grows.
Correctness
Correctness comes first: the steps must return the proper result for the inputs they are meant to handle. For example, a search cannot returnfalseafter inspecting only the first nonmatching item when other items remain unchecked.
Efficiency and Big O
Efficiency concerns resources such as running time and memory. Big O notation describes the broad growth of an algorithm's running time as an input of sizenbecomes larger, without depending on an exact count of milliseconds.
| Notation | Meaning | Example |
|---|---|---|
| Constant growth | Trie lookup when word length is treated as bounded |
| The remaining problem is repeatedly reduced, often by half | Binary search of sorted data |
| Work grows with the number of items | Scanning an array or copying it during insertion |
| Work grows roughly with the square of the input size | Comparison-based sorting approaches that repeatedly compare many items |
When a dictionary is ordered, is locating a word more like linear search or logarithmic search? Explain.
It is closer to logarithmic search because binary search can begin near the middle and repeatedly discard one half of the remaining ordered entries.
Pseudocode and Search
Pseudocode expresses an algorithm at a level between ordinary language and executable code. It can use familiar ideas such as variables, conditions, loops, and returns while leaving language-specific syntax aside.
FOR i FROM 0 TO n - 1
IF target IS BEHIND door[i]
RETURN true
RETURN falseIF target IS AT the middle
RETURN true
ELSE IF target IS LESS THAN the middle value
SEARCH the left half
ELSE IF target IS GREATER THAN the middle value
SEARCH the right halfBinary search depends on consistent ordering. Its self-referential search of a left or right half is an example of recursion: the same procedure is applied to a smaller version of the problem until little or nothing remains.
Programming Languages and Core Building Blocks
Programming languages supply precise syntax for expressing algorithms through reusable operations, decisions, repetition, stored values, and organized data.
Functions, Conditionals, and Loops
- Functions perform focused actions that can be combined into a larger solution. Their inputs are called arguments or parameters.
- A function may return a reusable value, or it may cause a side effect such as displaying text or producing sound.
- Conditionals choose a path according to a question's answer.
- Boolean expressions distinguish alternatives with results such as
trueorfalse. - Loops repeat an action, either while a condition remains true or for a finite number of iterations.
Variables and Data Types
A variable gives a name to a stored value. In C, the programmer declares the value's type so the program knows how to interpret its bits. A variable can later receive another value unless it is declared constant.
| Type | Purpose |
|---|---|
string | A sequence of characters; in CS50 it is an alias forchar *. |
int | An integer |
long | A larger integer type |
char | One character |
bool | A true-or-false value |
float | A floating-point value |
double | A floating-point value with more precision thanfloat. |
Memory, Pointers, and Arrays
RAM provides locations where data can be stored. A pointer holds the address of such a location, and dereferencing the pointer accesses the value found there. Hexadecimal is commonly used when displaying addresses.
An array stores elements of one declared type in contiguous memory. Its indices begin at0, so an array containingnelements ends at indexn - 1. Arrays created with a fixed size do not automatically grow.
C strings are character arrays ending with a null character. A string variable points to the first character, and the terminator reveals where that string ends.
Dynamic allocation obtains memory while a program runs.mallocrequests a contiguous block and returns its first address;freereturns that block to the operating system when it is no longer needed.
Data Structures
Data structures arrange information for particular operations. Their designs trade resources such as running time and memory, so the best choice depends on the task.
- Arrays place indexed elements next to one another in memory. Searching sorted arrays can use binary search, but growing an array may require allocating a new one and copying its elements.
- A linked list is assembled from nodes whose pointers lead to following nodes, allowing memory locations to be stitched together without one fixed contiguous array.
- Trees connect nodes hierarchically; related graph structures can use links in more than one direction.
- In a binary search tree, smaller values belong under the left child and larger values under the right child. Each node stores a value and two pointers.
- A hash table uses an array of buckets that can point to linked lists. Its hash rule chooses a bucket, and collisions occur when multiple values choose the same one.
- A trie builds a tree from arrays and follows successive characters of a word. This supports prefix-oriented navigation but consumes additional space.
- Queues are another common structure used in both programs and familiar real-world processes.
If a collection must be expanded frequently, what limitation of a fixed array makes a linked structure worth considering?
A full fixed array may require a new allocation followed by copying all existing elements. Linked nodes can instead be connected through pointers, though that design carries its own memory and access trade-offs.
Debugging
- Add
printfcalls to expose values and execution progress. - Use a debugger to pause and move through code. Step Over advances by a line, while Step Into enters a function call.
- Explain the program aloud to a rubber duck or another listener to uncover illogical reasoning.
- Use Valgrind to detect memory errors and leaks that ordinary output may not reveal.
Software Development Tools
Programmers use specialized environments to write, translate, run, and inspect code.
Text Editors and IDEs
Source code is plain text, so programming tools avoid word-processing decoration that has no effect on program behavior. A text editor supports writing code, while an integrated development environment combines editing with additional development capabilities. Visual Studio Code is one example.
Compilers and Build Utilities
A compiler converts human-readable source code into machine code. C uses this workflow, andclangis the compiler demonstrated in the course.
Themakeutility simplifies compilation by running the needed compiler command. Libraries may also need to be linked so their compiled code becomes available to the program.
Command-Line Interaction
A terminal provides a keyboard-driven interface for running programs and supplying arguments. Text commands are useful for speed and automation. For example,rm a.outruns the removal program witha.outas its command-line argument.
Compiled and Interpreted Languages
C normally exposes a separate compilation step. Python is generally described as interpreted because the programmer can run source code without manually compiling it first. Python also infers variable types and offers higher-level abstractions, while C remains useful when low-level control and performance are priorities.
Web Development
Web applications combine browser languages, network communication, server-side frameworks, and structured data tools.
HTML, CSS, and JavaScript
- HTML provides a page's content and structure.
- CSS controls the page's presentation.
- JavaScript adds behavior and can inspect or modify the web document.
The DOM, or Document Object Model, presents a web page as objects that JavaScript can select. For example,document.querySelectorcan locate an element, and.valuecan retrieve text entered into it.
HTTP Communication
- A
GETrequest asks for a resource. - A
POSTrequest submits information to the server. - A response status such as
200 OKreports the outcome;200means the request succeeded. - HTTP headers are key-value metadata sent with requests and responses.
- The
Content-Typeheader can identify formats such astext/html,image/jpeg,image/png, orvideo/mp4.
Frameworks and Flask
A framework supplies reusable structure for building applications. Flask is a Python web framework that can receive HTTP requests and choose what content to render.
Flask can follow the model-view-controller pattern. The controller contains decision-making logic, while HTML templates serve as views. This arrangement separates responsibilities within the application.
Relational Databases and SQL
A relational database organizes information in rows and columns and is designed to work with data at a scale that ordinary spreadsheets may struggle to handle. SQL is a language for operating on this structured data.
| Operation | Purpose | SQL command |
|---|---|---|
| Create | Add data | INSERT |
| Read | Retrieve data | SELECT |
| Update | Change stored data | UPDATE |
| Delete | Remove data | DELETE |
An index prepares an additional lookup structure for columns that are searched often. SQLite may use a wide, shallow B-tree so it can locate values more quickly, although building the index itself requires time and memory.
Abstraction
Functions, libraries, frameworks, and built-in data structures all provide abstraction. For example, a Python dictionary offers hash-table-like behavior without requiring each program to recreate the underlying low-level machinery.
Why can a higher-level abstraction make development faster even when a lower-level language offers more direct control?
The abstraction supplies capabilities that someone else has already implemented, allowing the programmer to spend more time on the problem instead of rebuilding low-level operations.
Common misconceptions
Watch out: A particular pattern of bits always represents the same kind of information.
Instead: Meaning depends on context. A program or data type may interpret the same pattern as a number, text, color, address, or instruction.
Watch out: A computer can inspect an entire array at once, just as a person can glance across a diagram.
Instead: The program must access memory locations methodically. A search algorithm determines which indexed locations to inspect and in what order.
Watch out: Assigning one pointer variable to another produces a separate copy of the referenced data.
Instead: The assignment copies the address. Both pointers can therefore lead to the same memory until new storage is allocated and the contents are copied.
Watch out: Sorting data first always makes a later search more efficient overall.
Instead: Binary search benefits from sorted data, but sorting also costs work. If only one search is needed, sorting first may not save time.
Lesson recap
- Computer science frames problems as inputs transformed into outputs by a process.
- Binary patterns represent many kinds of information, and context determines their meaning.
- Algorithms must be correct; Big O notation helps compare how their running times grow.
- Functions, conditions, Boolean expressions, loops, variables, and data types provide core programming vocabulary.
- Pointers, arrays, linked nodes, trees, hash tables, and tries organize memory with different performance trade-offs.
- Editors and IDEs support writing code, compilers translate it, build utilities automate commands, and debuggers expose mistakes.
- HTML, CSS, and JavaScript form browser-facing layers; HTTP connects clients and servers; Flask supplies application structure; SQL manages relational data.
- Abstraction packages lower-level details into reusable tools so developers can work at a more manageable level.