💻

CS50 Week 1: Introduction to C Programming

Mar 12, 2025

CS50 Week 1 Lecture Notes

Introduction

  • Week 1 builds upon concepts from Week 0.
  • Transition from Scratch to C programming language.
  • Core programming concepts such as functions, conditionals, loops, and variables from Scratch are now translated into C.
  • Programming involves converting source code to machine code (0s and 1s).
  • Compilers are tools that translate source code to machine code.

Programming Environment

  • Use of VS Code in a cloud-based environment (cs50.dev) with a GitHub account.
  • VS Code features: file explorer, code editor, and terminal window.
  • Introduction to command line interface (CLI).
  • Importance of terminal commands like ls, cd, mkdir, mv, rm.

Writing C Programs

  • Hello World in C:
    • Syntax: printf("Hello, world\n");
    • Requires #include <stdio.h> for input/output functions.
    • Functions: printf as equivalent to Scratch's say.
    • Escape Sequences: new line \n, quote \", backslash \\.

User Input and Variables

  • Use of CS50's library functions like get_string, get_int for user input.
  • Variables in C have types: int, char, string, etc.
  • Example: Reading user input and printing personalized messages.
  • Format specifiers in printf: %s for strings, %i for integers.

Conditionals

  • If-Else Statements: Similar to Scratch’s condition blocks.
  • Syntax: if (condition) {...} else if (condition) {...} else {...}
  • Example: Comparing two numbers and printing results.
  • Importance of logical operators: ==, !=, >, <, <=, >=.

Loops

  • While Loops:
    • Syntax: while (condition) {...}
    • Example: Counting down or up for repeated tasks.
  • For Loops:
    • Syntax: for (initialization; condition; increment) {...}
    • Example: Printing patterns or repeated actions.
  • Do-While Loops: Ensures code runs at least once.
  • Example: Implementing a get_positive_int function.

Functions

  • Defining custom functions:
    • Syntax: return_type function_name(parameters) {...}
    • Example: Creating a meow function to print sound effects.
  • Prototypes: Necessary to declare functions above main().
  • Importance in modularizing and reusing code.

Style and Design

  • Code should be correct, well-designed, and well-styled.
  • Use of tools like check50, style50, and design50 in CS50.

Practical Examples

  • Mario: Printing pyramids using loops.
  • Calculator: Implementing basic arithmetic with user input.
  • Handling integer overflow and floating-point precision issues.

Common Issues and Solutions

  • Integer Overflow: Limited by 32/64-bit storage.
  • Floating-Point Precision: Limitations in representing decimals.
  • Historical examples like the Boeing 787 and Pac-Man.
  • Future concerns like the Year 2038 Problem.

Conclusion

  • Emphasized understanding fundamental concepts over syntax.
  • Previewed common challenges in computing with real-world examples.