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

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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:

  1. 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. .c is the standard extension for C source code files.

    • Convention: Filenames are typically lowercase with no spaces (e.g., my_program.c).

  2. Write the code: Type the following C code into the hello.c tab:

      #include <stdio.h>
    
      int main(void)
      {
          printf("hello, world\n");
      }
    • VS Code automatically saves your changes, but you can also use Ctrl + S (or Cmd + S).

    • The File Explorer will show hello.c as a newly created file.

  3. Compile the code: In the terminal, type make hello.

    • make: A utility that simplifies the compilation process. It will find hello.c and use a compiler (like clang or gcc) 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.

  4. 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, world to the screen.

📜 Essential Terminal Commands

Beyond code, make, and ./, here are other useful CLI commands:

Command

Description

Example

ls

List files and directories in the current location.

ls

cd

Change directory. Navigate between folders.

cd hello

cp

Copy files or directories.

cp file1.c file2.c

mkdir

Make directory. Create a new folder.

mkdir my_folder

mv

Move (or rename) files or directories.

mv old.c new.c

rm

Remove (delete) files.

rm hello

rmdir

Remove directory (only if empty).

rmdir my_folder

clear

Clears the terminal screen.

clear

Ctrl + L

Keyboard shortcut to clear the terminal.


Up/Down

Navigate through previously typed commands.


Tab

Autocompletes commands or filenames.

code he + Tab

Ctrl + C

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 say block was a function that performed an action.

  • In C, printf is 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

  • \n is an escape sequence that represents a newline character. It moves the cursor to the beginning of the next line, similar to pressing Enter.

  • 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.h contains the declaration for printf, among other functions. Without including it, the compiler won't recognize printf and will generate an error (e.g., "undeclared identifier").

  • CS50.h: CS50 provides its own library (cs50.h) with helpful functions like get_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 from cs50.h that gets a string of text from the user.

    • "What's your name? ": The argument (input) to get_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_string returns the text typed by the user).

    • Variable: A named storage location in memory. answer is a variable.

    • string: The data type of the variable. In C, you must declare the type of a variable before using it. string means 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 the printf string. It tells printf to expect a string as a subsequent argument and plug it into that position.

    • , answer: The variable answer is passed as a second argument to printf, replacing %s.

    • printf can 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 (printf)

string

A sequence of characters (text). (From cs50.h)

%s

int

An integer (whole number).

%i

char

A single character (e.g., 'A', 'b', '7').

%c

float

A floating-point number (real number with decimal).

%f

double

A double-precision floating-point number (more precise than float).

%f

long

A long integer (larger range than int).

%li

bool

A Boolean value (true or false). (From stdbool.h)

(Not directly printed with %)

➕ Arithmetic Operators

Operator

Description

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Remainder (Modulo)

🧮 Comparison Operators (Boolean Expressions)

Operator

Description

Scratch Analog

<

Less than

< block

<=

Less than or equal to

(No direct block)

>

Greater than

> block

>=

Greater than or equal to

(No direct block)

==

Equality (two equals signs!)

= block

!=

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' block
  • if: Keyword to start a conditional.

  • Parentheses (): Contain the Boolean expression (a question that evaluates to true or false).

  • Curly Braces {}: Define the scope of the if block. 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 the if condition 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 x is not less than y and not greater than y, it must be equal to y. The final else handles this implicitly without needing else if (x == y).

  • Poor Design: Using separate if statements 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 single char literals. Double quotes "" are for string literals.


🔁 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 i for "integer" or counter) is set to an initial value before the loop.

  • Condition: The Boolean expression in while() is checked before each iteration. If true, the loop body executes. If false, 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 0 up 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> for true).

  • 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 for loop 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. If true, the loop repeats.

  • Scope: Variables declared inside a loop (e.g., int n = get_int(...)) only exist within that loop. To use n in the while condition, it must be declared outside the do block.


🧩 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 is void. If it doesn't take any input, its parameter list is (void).

  • int n: Specifies that the meow function expects an integer input, which will be referred to as n inside the function.

  • Function Prototype: The first line of a function, ending with a semicolon (e.g., void meow(int n);). This must be placed before main() so the compiler knows about the function when main() tries to call it.

  • Function Definition: The full implementation of the function, including its body in curly braces. Typically placed after main().

  • return Keyword: If a function is declared to return a specific type (e.g., int), it must use return 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 main function cleaner.

🌍 Scope

  • Scope: The region of a program where a variable is accessible.

  • Variables declared inside curly braces {} (e.g., within main() 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:

  1. 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.

  2. 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.

  3. 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;: Declares N as a constant integer.

  • The const keyword 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 for long).

  • 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., long instead of int), 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 / 3 is 0, 3 / 2 is 1).

  • 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 / y to perform floating-point division even if x and y are int).

  • Floating-Point Imprecision: Even with float or double, 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.3333333334326744079 instead of a perfect 0.333...).

  • Solution: Use double for 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., 99 for 1999 rolling over to 00 for 1900 or 2000).

  • 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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent