Introduction to C Programming
🚀 CS50 Week 1: Introduction to C Programming
This week marks the transition from visual block-based programming in Scratch to text-based coding in C, a powerful and fundamental programming language. The core concepts learned in Scratch, such as functions, conditionals, loops, and variables, are directly transferable, even if the syntax is more cryptic.
📝 From Scratch to C: "Hello, World!"
The familiar "Hello, World!" program, which was a simple drag-and-drop in Scratch, now appears as a structured text file in C.
The orange when green flag clicked block in Scratch corresponds to a specific structure in C, and the purple say block translates to a C function.
💻 Source Code and Machine Code
Source Code: Human-readable code written by programmers (like the C code above).
Machine Code: Binary instructions (zeros and ones) that computers directly understand.
Computers only understand zeros and ones. Therefore, source code must be translated into machine code. Patterns of bits represent not only data (numbers, letters, images) but also fundamental instructions like "print" or "save."
⚙️ The Compiler: Bridging the Gap
To transform source code into machine code, we use a special program called a compiler.
Input: Source code (e.g., in C).
Output: Machine code (zeros and ones).
Tool: The compiler translates one to the other. For C, we use a C compiler.
☁️ The CS50 Integrated Development Environment (IDE)
For CS50, we use a cloud-based version of Visual Studio Code (VS Code), accessible at cs50.dev. This environment is pre-configured with necessary software and tools.
Key components of the VS Code interface:
Code Tabs (Top Right): Where you write your code. VS Code automatically highlights (colorizes) code to improve readability and draw attention to different elements.
Terminal Window (Bottom): A Command Line Interface (CLI) where you type commands to interact with the computer. This is often more efficient than using a mouse for many programming tasks.
File Explorer (Top Left): A graphical interface to manage files and folders, similar to what you'd find on a desktop OS.
Activity Bar (Left): Icons for various features, including the CS50 Duck, a chatbot for assistance.
🌐 GUI vs. CLI
Graphical User Interface (GUI): Uses icons, buttons, and menus (e.g., File Explorer, most modern applications).
Command Line Interface (CLI): Text-based interface where you type commands (e.g., the Terminal window). While initially feeling like a step backward, CLIs offer greater power and efficiency for many programming tasks.
🚀 Running Your First C Program
Let's break down the process of writing and executing "Hello, World!" in C:
Create the file: In the terminal, type
code hello.c.code: A VS Code-specific command to open/create a file.hello.c: The name of the file..cis the standard extension for C source code files.Convention: Filenames are typically lowercase with no spaces (e.g.,
my_program.c).
Write the code: Type the following C code into the
hello.ctab:#include <stdio.h> int main(void) { printf("hello, world\n"); }VS Code automatically saves your changes, but you can also use
Ctrl + S(orCmd + S).The File Explorer will show
hello.cas a newly created file.
Compile the code: In the terminal, type
make hello.make: A utility that simplifies the compilation process. It will findhello.cand use a compiler (likeclangorgcc) to translate it into machine code.If successful, nothing will explicitly print to the terminal, which is a good sign.
The File Explorer will now show a new file named
hello(without.c), which is your executable machine code program.
Execute the program: In the terminal, type
./hello../: Tells the computer to look for the program in the current directory.hello: The name of the executable program.The program will run and print
hello, worldto the screen.
📜 Essential Terminal Commands
Beyond code, make, and ./, here are other useful CLI commands:
Command | Description | Example |
|---|---|---|
| List files and directories in the current location. |
|
| Change directory. Navigate between folders. |
|
| Copy files or directories. |
|
| Make directory. Create a new folder. |
|
| Move (or rename) files or directories. |
|
| Remove (delete) files. |
|
| Remove directory (only if empty). |
|
| Clears the terminal screen. |
|
| Keyboard shortcut to clear the terminal. | |
| Navigate through previously typed commands. | |
| Autocompletes commands or filenames. |
|
| Interrupt or cancel a running program (useful for infinite loops). |
🏗️ Deconstructing C: Functions and Syntax
Let's examine the "Hello, World!" code line by line and relate it back to Scratch concepts.
📦 Functions: printf
In Scratch, the
sayblock was a function that performed an action.In C,
printfis a function (part of the Standard I/O Library) that prints formatted output to the console.Parentheses
(): In C, these denote the input (or arguments) passed to a function, similar to the white ovals in Scratch blocks.Double Quotes
"": Strings of text in C must be enclosed in double quotes.Semicolon
;: Most statements in C must end with a semicolon, marking the end of a "thought" or instruction. This is a common source of errors for beginners.
\n: The Newline Escape Sequence
\nis an escape sequence that represents a newline character. It moves the cursor to the beginning of the next line, similar to pressingEnter.Without
\n, the terminal prompt ($) would appear immediately after the output, on the same line.Other escape sequences:
\r: Carriage return (moves cursor to beginning of current line).\": Prints a literal double quote.\': Prints a literal single quote.\\: Prints a literal backslash.
📚 Libraries: #include <stdio.h>
#include <stdio.h>: This line tells the C compiler to include the Standard Input/Output (stdio) library.Header Files (
.h): These files contain declarations (prototypes) of functions and other components that are part of a library. They tell the compiler how to use functions defined elsewhere.stdio.hcontains the declaration forprintf, among other functions. Without including it, the compiler won't recognizeprintfand will generate an error (e.g., "undeclared identifier").CS50.h: CS50 provides its own library (cs50.h) with helpful functions likeget_string,get_int, etc., which simplify common tasks like getting user input.
📖 CS50 Manual Pages
manual.cs50.io: A user-friendly online documentation for C and CS50 library functions.Synopsis: Shows the header file to include and the function's prototype.
Description: Explains how the function works.
🔄 Input and Output: Return Values
get_string("What's your name? "):get_string: A function fromcs50.hthat gets a string of text from the user."What's your name? ": The argument (input) toget_string, displayed as a prompt to the user.The space after the question mark ensures the user's input doesn't immediately butt up against the prompt.
string answer = ...:Return Value: Functions can return a value (e.g.,
get_stringreturns the text typed by the user).Variable: A named storage location in memory.
answeris a variable.string: The data type of the variable. In C, you must declare the type of a variable before using it.stringmeans it will store text.Assignment Operator
=: Assigns the value from the right side to the variable on the left side.
printf("hello, %s\n", answer);:%s: A format code (or placeholder) within theprintfstring. It tellsprintfto expect a string as a subsequent argument and plug it into that position., answer: The variableansweris passed as a second argument toprintf, replacing%s.printfcan take multiple arguments, separated by commas, to fill multiple placeholders.
📊 Data Types and Operators
C requires explicit declaration of data types for variables.
🏷️ Common Data Types
Type | Description | Format Code ( |
|---|---|---|
| A sequence of characters (text). (From |
|
| An integer (whole number). |
|
| A single character (e.g., 'A', 'b', '7'). |
|
| A floating-point number (real number with decimal). |
|
| A double-precision floating-point number (more precise than |
|
| A long integer (larger range than |
|
| A Boolean value ( | (Not directly printed with |
➕ Arithmetic Operators
Operator | Description |
|---|---|
| Addition |
| Subtraction |
| Multiplication |
| Division |
| Remainder (Modulo) |
🧮 Comparison Operators (Boolean Expressions)
Operator | Description | Scratch Analog |
|---|---|---|
| Less than |
|
| Less than or equal to | (No direct block) |
| Greater than |
|
| Greater than or equal to | (No direct block) |
| Equality (two equals signs!) |
|
| Not equal to | (No direct block) |
=(single equals): Used for assignment (e.g.,int x = 5;).==(double equals): Used for comparison (e.g.,if (x == 5)). This distinction is crucial to avoid common bugs.
🔢 Variables: Declaration and Initialization
Declaration: Telling the computer a variable exists and its type (e.g.,
int counter;).Initialization: Giving a variable its first value (e.g.,
counter = 0;).Can be combined:
int counter = 0;.
Incrementing/Decrementing Variables
counter = counter + 1;counter += 1;(Syntactic sugar for adding a value)counter++;(Most common for adding 1; only adds 1)counter--;(Subtracts 1)
🚦 Conditionals: Making Decisions
Conditionals allow programs to make decisions and execute different code paths based on whether a condition is true or false, similar to "forks in the road."
if Statement
if (x < y) // Boolean expression in parentheses
{
// Code to execute if x is less than y
printf("x is less than y\n");
} // Curly braces define the scope of the 'if' blockif: Keyword to start a conditional.Parentheses
(): Contain the Boolean expression (a question that evaluates totrueorfalse).Curly Braces
{}: Define the scope of theifblock. All code inside these braces will execute if the condition is true.Indentation: Not strictly required by the compiler but crucial for readability and good style.
if-else Statement (Two-way Fork)
if (x < y)
{
printf("x is less than y\n");
}
else // 'else' does not need parentheses
{
printf("x is not less than y\n");
}else: Executes its block of code if theifcondition is false.
if-else if-else Statement (Multi-way Fork)
if (x < y)
{
printf("x is less than y\n");
}
else if (x > y) // Another condition
{
printf("x is greater than y\n");
}
else // Catch-all if previous conditions are false
{
printf("x is equal to y\n");
}Design Principle: Avoid redundant checks. If
xis not less thanyand not greater thany, it must be equal toy. The finalelsehandles this implicitly without needingelse if (x == y).Poor Design: Using separate
ifstatements for each condition (e.g.,if (x < y),if (x > y),if (x == y)). This forces the computer to check all conditions, even if an earlier one was true, leading to unnecessary work and potentially multiple outputs.
🤝 Logical Operators
Combine multiple Boolean expressions:
Operator | Description |
|---|---|
| Logical AND (both conditions must be true) |
` | |
| Logical NOT (inverts a Boolean value) |
Example: Handling Case-Insensitive Input
char c = get_char("Do you agree? ");
if (c == 'y' || c == 'Y') // Checks if c is 'y' OR 'Y'
{
printf("Agreed.\n");
}
else if (c == 'n' || c == 'N') // Checks if c is 'n' OR 'N'
{
printf("Not agreed.\n");
}Single Quotes
'': Used for singlecharliterals. Double quotes""are forstringliterals.
🔁 Loops: Repeating Actions
Loops allow a block of code to be executed repeatedly.
while Loop
The most direct translation of Scratch's repeat until or forever blocks.
int i = 3; // Initialize a counter variable
while (i > 0) // Condition to continue looping
{
printf("meow\n");
i--; // Decrement the counter (or i = i - 1; or i -= 1;)
}Initialization: A variable (often
ifor "integer" orcounter) is set to an initial value before the loop.Condition: The Boolean expression in
while()is checked before each iteration. Iftrue, the loop body executes. Iffalse, the loop terminates.Update: Something inside the loop body must change the variable used in the condition, eventually making the condition false, to prevent an infinite loop.
Conventional Counting: Programmers often count from
0up to (but not including) a target number (e.g.,for (int i = 0; i < 3; i++)).
Infinite Loops
To create an infinite loop:
while (true)(requires#include <cs50.h>fortrue).To stop an out-of-control program in the terminal: Press
Ctrl + C.
for Loop
A more concise way to write loops when you know the number of iterations in advance.
for (int i = 0; i < 3; i++) // Initialization; Condition; Update
{
printf("meow\n");
}Initialization:
int i = 0;(executed once at the start).Condition:
i < 3;(checked before each iteration).Update:
i++(executed after each iteration).Semicolons: Separate the three parts of the
forloop header.
do-while Loop
Executes the loop body at least once before checking the condition. Useful for getting valid user input.
int n; // Declare 'n' outside the loop's scope
do
{
n = get_int("Number: "); // Assign value inside the loop
}
while (n < 1); // Condition to continue looping (if n is invalid)The code inside
do { ... }always runs first.The
while (condition);is checked after the first execution. Iftrue, the loop repeats.Scope: Variables declared inside a loop (e.g.,
int n = get_int(...)) only exist within that loop. To usenin thewhilecondition, it must be declared outside thedoblock.
🧩 Functions: Abstraction and Reusability
Functions allow you to break down complex problems into smaller, manageable, and reusable pieces.
Defining Your Own Functions
// Function prototype (declaration) - tells C about the function
void meow(int n);
int main(void)
{
// Call the meow function, passing 3 as an argument
meow(3);
}
// Function definition (implementation) - the actual code
void meow(int n) // 'void' = no return value; 'int n' = takes an integer input
{
for (int i = 0; i < n; i++)
{
printf("meow\n");
}
}void: If a function does not return a value, its return type isvoid. If it doesn't take any input, its parameter list is(void).int n: Specifies that themeowfunction expects an integer input, which will be referred to asninside the function.Function Prototype: The first line of a function, ending with a semicolon (e.g.,
void meow(int n);). This must be placed beforemain()so the compiler knows about the function whenmain()tries to call it.Function Definition: The full implementation of the function, including its body in curly braces. Typically placed after
main().returnKeyword: If a function is declared to return a specific type (e.g.,int), it must usereturn some_value;to send a value back to the caller.
Example: get_positive_int
// Prototype
int get_positive_int(void);
int main(void)
{
int num_meows = get_positive_int(); // Call the function, store its return value
meow(num_meows); // Pass the stored value to meow
}
// Definition
int get_positive_int(void) // Returns an int, takes no input
{
int n;
do
{
n = get_int("Number: ");
}
while (n < 1);
return n; // Explicitly return the valid integer
}This function encapsulates the logic for repeatedly asking for a positive integer, making the
mainfunction cleaner.
🌍 Scope
Scope: The region of a program where a variable is accessible.
Variables declared inside curly braces
{}(e.g., withinmain()or a specific loop) are local to that scope and cannot be accessed outside of it.This prevents accidental modification of variables and promotes modular code.
🌟 Code Quality: Correctness, Design, and Style
When writing code, consider these aspects:
Correctness: Does the code produce the desired output and behave as expected for all valid inputs?
check50: A CS50 tool to automatically test code correctness.
Design: How well-structured and efficient is the code? Does it make good decisions?
design50: A CS50 tool (via the Duck) that provides qualitative advice on code design.
Style: Is the code readable and consistently formatted?
style50: A CS50 tool that formats your code according to CS50's style guide.
✍️ Comments
//: Starts a single-line comment./* ... */: Creates a multi-line comment block.Comments are ignored by the compiler but provide human-readable notes, explanations, or reminders within the code.
🚫 Constants
const int N = 3;: DeclaresNas a constant integer.The
constkeyword prevents the variable's value from being changed after initialization. This helps prevent accidental bugs and clarifies intent.Avoid "magic numbers" (hard-coded numbers used repeatedly) by defining them as constants at the top of your code.
⚠️ Real-World Problems: Limitations of Computers
Even seemingly simple arithmetic can expose fundamental limitations of computers due to their finite memory.
📈 Integer Overflow
Computers represent numbers using a fixed number of bits (e.g., 32 bits for
int, 64 bits forlong).Integer Overflow: Occurs when an arithmetic operation attempts to create a numerical value that is too large to be represented within the allocated number of bits.
When an integer overflows, it "wraps around" to the minimum possible negative value or zero, leading to unexpected and often catastrophic results (e.g., the Boeing 787 bug, Pac-Man's kill screen).
Solution: Use data types that can store larger numbers (e.g.,
longinstead ofint), or specialized libraries for "big integers" if available in the language.
📉 Floating-Point Imprecision (Truncation)
Truncation: When dividing integers, C discards any fractional part (e.g.,
1 / 3is0,3 / 2is1).Floating-Point Numbers (
float,double): Designed to store real numbers with decimal points.Casting: Temporarily treating a variable of one type as another (e.g.,
(float)x / yto perform floating-point division even ifxandyareint).Floating-Point Imprecision: Even with
floatordouble, computers cannot perfectly represent all real numbers due to their finite number of bits. This can lead to subtle inaccuracies in calculations (e.g.,0.3333333334326744079instead of a perfect0.333...).Solution: Use
doublefor higher precision, or specialized libraries for arbitrary-precision arithmetic in scientific computing.
🗓️ The Y2K38 Problem
Similar to the Y2K problem (Year 2000 problem), where systems only stored two digits for years (e.g.,
99for1999rolling over to00for1900or2000).Many systems store time as the number of seconds since January 1, 1970, using a 32-bit integer.
On January 19, 2038, this 32-bit counter will overflow, potentially causing widespread system failures.
Solution: Migrate systems to use 64-bit integers for timekeeping.

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