1. Home
  2. Explore
  3. Computer Science
  4. Introduction to Programming

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Content

Introduction to Programming

🚀 CS50 Week 1: From Binary to C

This week introduces fundamental programming concepts, transitioning from the machine's binary language to higher-level abstractions. It revisits concepts covered with Scratch and applies them to the C programming language, highlighting the importance of precision and understanding underlying computer operations.

💾 Machine Language & Abstraction

Machines fundamentally understand only binary (0s and 1s). However, human-created abstractions allow programmers to write code at a much higher level, such as with Scratch and now C, without needing to directly manipulate binary. This abstraction makes programming more accessible and efficient.

  • Binary represents two states: on/off, 1/0, true/false, similar to a light bulb. Multiple 'light bulbs' (bits) can be permuted to represent larger numbers.

  • ASCII is an abstraction mapping numbers (represented in binary) to characters, allowing text to be stored and displayed. Similarly, colors in graphics programs are represented by numerical values (e.g., RGB components) which are fundamentally binary.

The value of abstraction lies in not needing to think at the lowest level of detail once a problem is solved. For instance, once an image is represented as pixels and colors, we can then represent animations as sequences of images, building layers of abstraction.

✍️ Algorithms and Pseudocode

Algorithms are the 'secret sauce' within a program where problems are actually solved. Pseudocode, an informal, succinct, English-like description, helps express algorithms without strict syntax. Key programming concepts like loops, conditions, and variables are foundational to expressing algorithms.

  • Efficiency of algorithms matters. Comparing methods like sequential search (linear time) versus binary search (logarithmic time) demonstrates how different approaches can drastically impact performance.

  • Abstractions in pseudocode (e.g., 'open to the middle of the phone book,' 'call Mike') are useful but can lead to ambiguity. For computers, instructions need extreme precision to avoid errors.

The 'peanut butter and jelly sandwich' exercise illustrates how human assumptions and abstractions, while natural for us, require explicit and detailed instruction for a computer or a new learner to execute correctly. Missing specificity or precision leads to program errors or unexpected behavior.

💻 Transitioning from Scratch to C

C is an older, text-based, and more powerful language compared to Scratch. While its syntax may appear cryptic initially, the underlying programming principles remain consistent with what was learned in Scratch. The focus should be on understanding these principles rather than getting frustrated by syntax.

📜 C Syntax vs. Scratch Blocks

  • Output (Say/Print): Scratch's 'say' block translates to `printf("Hello, world\n");` in C. `\n` is an escape character for a newline, and strings require double quotes. Most C statements end with a semicolon (`;`).

  • Variables: Declaring a variable in C requires specifying its type (e.g., `int counter = 0;`). `int` signifies an integer. Variables must be declared before use. `counter = counter + 1;` or `counter += 1;` or `counter++;` all increment the variable.

  • Conditions: Scratch's 'if-then-else' blocks translate to `if (condition) { ... } else { ... }` in C. Boolean expressions (e.g., `x < y`) are enclosed in parentheses. Curly braces `{}` define code blocks. Equality is checked using a double equals sign `==` (single `=` is for assignment).

The `if-else if-else` structure handles multiple conditions. An `else` block serves as the default case if preceding conditions are false. Optimizing by removing redundant conditions (e.g., the final `else if` for equality if only three outcomes are possible) can improve efficiency, though readability sometimes takes precedence.

  • Loops: Scratch's 'forever' loop is `while (true) { ... }` in C. The `true` keyword ensures the loop continues indefinitely. 'Repeat N times' loops are implemented using `for` loops: `for (int i = 0; i < N; i++) { ... }`. C conventions often start counting from 0.

  • User Input: Scratch's 'ask and wait' block uses a built-in 'answer' variable. In C, functions like `get_string("What is your name?\n")` (from CS50 library) obtain input. The returned value must be stored in a declared variable (e.g., `string name = get_string("...");`).

The `printf` function supports 'format codes' like `%s` (for string), `%i` (for integer), and `%f` (for float) to insert variable values into a string. For example: `printf("Hello, %s\n", name);`.


🛠️ Compiling and Running C Code

Unlike Scratch, C requires a separate step to convert human-readable 'source code' into machine-executable 'machine code' (0s and 1s). This process is called 'compilation'.

  • Source Code: The C code written by humans (e.g., `hello.c`).

  • Compiler: A program (like `clang`) that takes source code as input and produces machine code as output. For example: `clang hello.c` (creates an executable `a.out`) or `clang -o hello hello.c` (creates an executable `hello`).

  • Running Executable: Machine code is executed in a terminal using `./a.out` or `./hello`. The `make` command (e.g., `make hello`) automates the compilation process, making it simpler for the programmer.

The CS50 Sandbox provides a web-based environment with a code editor (top) and a terminal window (bottom) for writing, compiling, and running C programs. Errors during compilation often indicate syntax mistakes, and it's best to address them from the top of the error messages.

🧩 Functions and Libraries

Functions are reusable blocks of code that perform specific tasks. They can take inputs (arguments/parameters) and return outputs (return values).

  • Including Libraries: C programs often use functionality from 'libraries.' For example, `stdio.h` (Standard Input/Output) provides `printf`, and `cs50.h` (CS50 library) provides `get_string`, `get_int`, `get_float`, `get_char`, and the `string` data type.

  • Defining Custom Functions: Programmers can create their own functions (e.g., `void cough(int n)`). The `void` keyword indicates no return value or no input. Functions must be declared (prototyped) before they are called, or defined before being called by other functions in the same file. Prototypes (e.g., `void cough(int n);`) provide enough information for the compiler to know a function exists, allowing its definition to appear later in the code.

🔢 Data Types and Arithmetic

C supports various data types beyond just integers and strings.

  • Integers (`int`): Whole numbers. Arithmetic operations: `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `%` (remainder/modulo).

  • Floating-point Numbers (`float`, `double`): Numbers with decimal points. `float` typically uses 32 bits, while `double` uses 64 bits for greater precision.

  • Characters (`char`): Single characters. Boolean (`bool`): True/false values.

⚠️ Precision and Overflow Issues

Computers have finite memory, leading to limitations in representing numbers.

  • Floating-Point Imprecision: An infinite number of real numbers cannot be represented with finite memory. This leads to slight inaccuracies, where numbers like 0.2 might be stored as `0.20000000298023223876953125`. This is critical in scientific or financial applications. Consequently, floating-point numbers should generally not be compared for exact equality.

  • Integer Overflow/Underflow: When an integer exceeds the maximum value it can store (e.g., 32 bits can hold roughly 4 billion), it 'overflows' and wraps around to a negative or zero value. Similarly, subtracting from the minimum value leads to 'underflow' and wraps around to a positive maximum. This has led to real-world bugs, like the Boeing 787 grounding or the 'Nuclear Gandhi' bug in Civilization.

Programmers must anticipate these limitations and implement logic to handle them, such as using larger data types (like `long` for 64-bit integers or `double` for more precise decimals) or enforcing value constraints.

Scope and Comments

  • Scope: Variables only exist within the curly braces where they are declared. This limits their accessibility to specific parts of the code.

  • Comments: Lines starting with `//` are comments, ignored by the compiler. They are crucial for human readability, explaining complex code or reminding oneself of the code's purpose.

🎯 Looking Ahead

The first problem set will involve programming in C using the CS50 Lab environment, applying the concepts introduced in this lecture. Despite initial frustration with syntax, the focus remains on understanding programming ideas and the satisfaction of building something functional.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesContent