Introduction to C Programming


Introduction to C Programming

Michael
Alright, so we're diving into the exciting world of programming today, transitioning from the visual, user-friendly Scratch to a more traditional language called C. It's week one, and we're finally getting our hands dirty with actual code.

Hope
That's right, Michael! Scratch was a fantastic way to grasp fundamental concepts like functions, conditionals, loops, and variables. It planted those visual ideas in our minds, making the transition to text-based coding a bit less daunting, even if the syntax looks more cryptic at first.

Michael
Exactly. We're moving from dragging and dropping puzzle pieces to writing actual source code. For example, the 'Hello, world' program we made in Scratch will now look like a series of lines of text in C. It's definitely a different feel.

Hope
And it's important to remember that computers don't understand this human-readable source code directly. They only understand binary, those zeros and ones. So, there's a crucial step involved in translating our C code into machine code that the computer can execute.

Michael
That's where the compiler comes in! It's a special program designed to translate our source code into the binary machine code. We'll be using a specific compiler for the C language.

Hope
And for our programming environment, we're using CS50.dev, which is a cloud-based version of Visual Studio Code, or VS Code. It's an industry-standard tool, pre-configured with everything we need, which saves us a lot of setup headaches.

Michael
VS Code is quite powerful. It offers features like syntax highlighting, which colorizes our code to make it easier to read, and a file explorer. But a key new interface for us will be the command line interface, or CLI, accessed through the terminal window.

Hope
The CLI might feel like a step backward initially, since we're used to clicking icons. But it offers more power and efficiency in the long run. We'll be typing commands directly to interact with our programs.

Michael
To create our first C file, we'll type `code hello.c` in the terminal. The `.c` extension is a convention for C files. It's crucial to pay attention to capitalization and spaces, as computers aren't forgiving!

Hope
Once we've written our C code in `hello.c`, the next step is to compile it. We'll use the `make hello` command. This invokes the compiler to convert our source code into an executable machine code file, also named `hello`.

Michael
And finally, to run our program, we type `./hello` in the terminal. The `./` simply tells the computer to look for the executable file in the current directory. So, it's a three-step process: write, compile, run.

Hope
It's important to differentiate between `hello.c` and `hello`. `hello.c` is the source code we write, human-readable. `hello` is the compiled machine code, understood by the computer. You can see both in the file explorer or by typing `ls` in the terminal.

Michael
Absolutely. If you try to open the `hello` file, you'll see a bunch of unreadable characters because it's binary machine code, not human-readable text. VS Code will even warn you about it.

Hope
Now, let's break down the actual 'Hello, world' C code. The `printf` function is similar to Scratch's 'say' block. It displays text on the screen. The text we want to display goes inside double quotes within the parentheses.

Michael
The ` ` at the end of 'Hello, world' is an escape sequence. It tells the computer to move the cursor to a new line after printing. Without it, your terminal's prompt would appear right after 'Hello, world' on the same line.

Hope
Escape sequences are special characters that tell the computer to do something specific, not just print the characters literally. For example, `"` prints a double quote within a string, and `\` prints a literal backslash.

Michael
At the top of our C file, we often see `#include <stdio.h>`. This line includes a 'header file' called `stdio.h`. It contains predefined functions, like `printf`, that someone else wrote for us, making our lives easier.

Hope
Without including `stdio.h`, our program wouldn't know what `printf` is, and the compiler would throw an error like 'undeclared library function printf'. It's like asking someone to do something they've never learned how to do.

Michael
CS50 also provides its own library, `cs50.h`, with helpful functions like `get_string` and `get_int`. These simplify getting input from the user, which can be a bit more complex in raw C.

Hope
This leads us to the concept of 'return values.' While `printf` has a 'side effect' of displaying text, functions like `get_string` return a value – the actual text the user typed. We need to store this in a 'variable'.

Michael
To declare a variable in C, you specify its 'type' and then its name. For example, `string answer = get_string("What's your name? ");` creates a variable `answer` of type `string` and assigns it the user's input.

Hope
Notice the semicolon at the end of that line. In C, semicolons are used to terminate statements, signaling the end of a thought to the compiler. Forgetting them is a common beginner mistake.

Michael
When we want to print a string stored in a variable, we use a 'placeholder' inside `printf`. For strings, it's `%s`. So, `printf("hello, %s\n", answer);` would print 'hello, ' followed by the value of the `answer` variable.

Hope
C also supports other data types, beyond just strings. We have `int` for integers, `char` for single characters, `float` and `double` for real numbers with decimal points, and `bool` for true/false values.

Michael
Let's talk about 'conditionals' – those proverbial forks in the road. In C, we use `if` statements. The condition goes inside parentheses, and the code to execute if true goes inside curly braces.

Hope
For a two-way fork, we use `if-else`. If the `if` condition is false, the code in the `else` block executes. And for multiple conditions, we can chain `if-else if-else` statements.

Michael
A crucial detail for comparison is using `==` for equality. A single `=` is for assignment, like assigning a value to a variable. So `if (x == y)` checks if `x` is equal to `y`.

Hope
When designing conditionals, it's good practice to avoid redundant checks. If `x` is not less than `y`, and not greater than `y`, it must be equal to `y`. So, a final `else` statement can often replace an `else if (x == y)`.

Michael
This highlights good code design. Writing less code, and avoiding unnecessary checks, generally makes your program more efficient and reduces the chance of errors. It's about logical elegance.

Hope
For single characters, we use the `char` data type and `get_char()` from the CS50 library. When comparing characters, you use single quotes, like `if (c == 'y')`. Double quotes are for strings.

Michael
If you want to handle both uppercase and lowercase input, you can use the logical OR operator, `||`. So `if (c == 'y' || c == 'Y')` checks for both 'y' and 'Y'.

Hope
We also have operators for comparisons like `>=` (greater than or equal to), `<=` (less than or equal to), and `!=` (not equal to). These are all fundamental to creating flexible conditional logic.

Michael
Variables are like containers for values. You declare them with a type, like `int counter = 0;`. To increment a variable, `counter = counter + 1;` or the shorthand `counter += 1;` or even `counter++;` if you're only adding one.

Hope
Now, let's talk about 'loops' – doing something repeatedly. In C, the `while` loop is similar to Scratch's `repeat` block. It executes a block of code as long as a condition remains true.

Michael
A common pattern for a `while` loop is to initialize a counter, set a condition, and then increment/decrement the counter within the loop. For instance, `int i = 0; while (i < 3) { ...; i++; }`.

Hope
Computer scientists often start counting from zero by convention. So `i = 0; i < 3; i++` is a very common way to repeat something three times, counting up to but not including the final number.

Michael
The `for` loop is another popular looping construct, often preferred when you know exactly how many times you want to repeat something. It condenses the initialization, condition, and increment into a single line.

Hope
For example, `for (int i = 0; i < 3; i++) { ... }` does the exact same thing as the `while` loop we just discussed. It's more compact but functionally identical.

Michael
If you want a loop to run forever, you can use `while (true)`. Just be aware that you'll need `Control-C` to break out of an infinite loop in your terminal! It's an important shortcut for canceling runaway programs.

Hope
Just like in Scratch, we can define our own functions in C. This allows us to abstract away complex logic into reusable blocks. For example, a `meow` function could simply print 'meow' to the screen.

Michael
A function definition in C looks like `void meow(void) { ... }`. The first `void` means the function doesn't return any value (only has side effects). The `(void)` in parentheses means it doesn't take any input.

Hope
When you define your own functions and place them after `main()`, you need to provide a 'prototype' at the top of your file. This tells the compiler about the function's existence and signature before it's actually defined.

Michael
The prototype is just the first line of your function, like `void meow(void);`, followed by a semicolon. It's a heads-up to the compiler, so it doesn't complain about an 'undeclared function' when it encounters your function call in `main()`.

Hope
To make functions more flexible, they can take inputs, or 'arguments'. For example, `void meow(int n)` means the `meow` function now accepts an integer `n` as input, allowing us to specify how many times the cat should meow.

Michael
A crucial concept in programming is 'scope'. Variables only exist within the curly braces where they are defined. A variable `n` in `main()` is distinct from a variable `n` in `meow()`, even if they share the same name.

Hope
This means you can't just access a variable defined in `main()` from within `meow()`. You have to explicitly pass it as an argument to the function.

Michael
For user input where you need to repeatedly prompt until valid input is given, the `do-while` loop is perfect. It executes the code block at least once, and then continues to loop while a condition is true.

Hope
For example, `do { n = get_int("Number: "); } while (n < 1);` will keep asking for a number until the user provides one that is at least 1. Remember to declare `n` outside the loop's scope so it's accessible afterwards.

Michael
We can even create our own reusable function, `get_positive_int()`, to handle this common task of getting valid positive integer input. This further modularizes our code.

Hope
This `get_positive_int()` function would have `int` as its return type because it's designed to hand back an integer to the caller. Inside the function, you'd use the `return` keyword, like `return n;`.

Michael
When grading code, we look for three things: Correctness, does it do what it's supposed to? Design, is it well-structured and efficient? And Style, is it readable and follows conventions?

Hope
CS50 provides tools like `check50` for correctness, `style50` for aesthetics, and `design50` for qualitative advice on improving your code. These tools help you produce high-quality work.

Michael
Moving onto more mathematical operations, computers excel at arithmetic. C supports addition `+`, subtraction `-`, multiplication `*`, division `/`, and the remainder operator `%`.

Hope
When dividing integers in C, be aware of 'truncation'. `1 / 3` will result in `0`, and `3 / 2` will be `1`, because the decimal part is simply cut off. It doesn't round.

Michael
To get accurate decimal results, you need to use 'floating-point' numbers, `float` or `double`. You can 'cast' an integer to a float for division, like `(float)x / y`, and use `%f` as the placeholder in `printf`.

Hope
Even with floats and doubles, there's a limit to 'floating-point precision'. Computers use a finite number of bits to represent these numbers, so some real numbers cannot be represented perfectly, leading to slight inaccuracies after many decimal places.

Michael
This ties into 'integer overflow', which we saw with the doubling money example. If you try to store a number larger than what the variable's allocated bits can hold, it 'wraps around', often becoming negative or zero.

Hope
This is a real-world problem! The Boeing 787 once had a software bug where a 32-bit counter, counting in tenths of seconds, would overflow after 248 days, causing loss of electrical power. The workaround was to reboot the plane!

Michael
Similarly, the original Pac-Man game only supported 255 levels because it used 8-bit integers. Level 256 would cause graphical glitches due to integer overflow.

Hope
And looking ahead, there's a 'Y2K38' problem coming. Many systems use 32-bit integers to count seconds since January 1, 1970. On January 19, 2038, these will overflow, potentially causing widespread system failures.

Michael
These issues highlight the importance of understanding how data types work and their limitations. Sometimes, simply using a `long` (64-bit integer) can postpone or solve the overflow problem, but even that has its limits.

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