Skip to content

CS50 Week 1: C

On compiling C, data types and the C 'grammar'.

Written by Eva Dee on (about a 3 minute read).

Compiling permalink

  • source code (C language) -> algorithm (compiler - clang) -> machine code (binary)

  • A program called a compiler will take source code as input and produce machine code as output.

  • clang -o hello hello.c -lcs50 -> make hello

  • Header files that end with .h refer to some other set of code, like a library, that we can then use in our program.

Data types permalink

  • bool for true or false

  • char single ASCI characters: take up 1 byte (8 bits)

  • int number: always take up 4bytes (32 bits) of memory

  • unsigned int is a qualifier - it doubles the positive range of values that an integer can take on (but doesn't allow for negative values). There are also other qualifiers like short, long, and const long really big number

  • float number with decimals, take up 4bytes (32 bits) of memory, caution: there's a limit to how precise we can be with floats

  • double number with many decimals, up to 8 bytes (64 bites) of memory

  • string (must #include <cs50.h>)

More complex types permalink

  • structs (structures)
  • typedefs (defined types)

πŸ€” How about void?

  • void is a type, but not a data type:

  • functions can have a void return type which means they don't returns a value (like printf)

  • functions with void as parameters simply take no parameter

Placeholders for data types permalink

  • %c char

  • %f float, double

  • %i int

  • %li long

  • %s string

Operators permalink

  • arithmetic operators

  • boolean expressions (logical operators: &&, ||, !, relational operators: >, >=, <, <=, ==, !=)

Conditional statements permalink

  • if, else if, else

  • switch statement

  • ternary operators

Loops permalink

  • while, do while, for

Misc permalink

  • type of output -> void main(void) <- type of input

  • All variables (when you declare them) need 2 things: type and name

  • declaration vs assignment vs initialization (declaring + assigning at the same time)

Command line permalink

  • ls, cd, pwd, mkdir, cp, rm, mv

πŸ€” What is a greedy algorithm?

  • A greedy algorithm is one β€œthat always takes the best immediate, or local, solution while finding an answer. Greedy algorithms find the overall, or globally, optimal solution for some optimization problems, but may find less-than-optimal solutions for some instances of other problems.”